PROOF: the kernel theorem from a covered path or loop run per thread (Kernel.sound_of_chains)
Lean: MojoProof/Sym/Kernel.lean and, for matmul kernels (13), MojoProof/Sym/KernelMat.lean, with
the scope of each statement given below and in the section
"Scope". Instances and twins: MojoProofTest/Kernel.lean, for a kernel whose thread runs a loop
MojoProofTest/KernelLoop.lean, for a kernel whose threads run a loop and store to cells apart
only on the storing threads MojoProofTest/KernelCells.lean, for a kernel whose threads run a loop
with fmul contract MojoProofTest/KernelContract.lean, and for 2-D cells and Elem.Out at the
end of a run MojoProofTest/KernelXY.lean. The section "Plan: the naive matmul's kernel theorem"
is a plan, not a proof. The section "Through collective calls" is the schedule through barriers
and warp shuffles (MojoProof/Sym/SchedWait.lean, MojoProofTest/SymWait.lean) and its plan. The command that generates a kernel's theorem from these is described in
docs/kernel.md.
The kernel theorem composes four facts proved once: the block checker's path theorem with
phis (Block.sound_retWith, MojoProof/Sym/Path.lean), the loop theorem for a thread through a
sequence of loops (Runs.of_chainsWith, MojoProof/Sym/Loop.lean), the sequential schedule by an
invariant (Seq.start_sound_inv, MojoProof/Sym/Sched.lean, which goes through
Grid.start_sound), and the shape of the threads the start makes (Grid.start_run,
MojoProof/Sem/Closed.lean). What is left to a kernel is per thread: which path or sequence of
loops it takes, that their premises hold (for a loop, from an invariant and a trip count), and
what its effects leave.
Statements
Runs.of_ret. Lettbe a thread with one framefof kernelfn, at blockland instructionp0, with noallocablocks, and let(l, ds, S) :: psbe a path that the path checker accepts fromp0(coversPathWith false P fn p0 … = true: each next block is covered from after itsphis when the edge enters it there) in a context whose program isP. If the path's premises hold on the entry valuation (WalkWith false: an edge into a block withphis sets them,Valuation.into), its last block's exit isret, and the last block's effects succeed at its entry valuation (Valuation.lastWith false) with a memorymeofQ(together:Ret V Q path), thentruns to its end frommleavingme(Runs c t m me), andQ me.Ret.mono: aRettoQis aRetto everyQ'that holds of every memory ofQ.Grid.start_thread. IfGrid.startgives gridg, every threadk < g.threads.sizeofg(Grid.thread g k) is⟨[f], 0⟩, wherefis a frame offnat the label offn's first block, at instruction 0, with noallocablocks.Kernel.sound_of_chains. Letpathsbe a list of paths, each starting atfn's first block and accepted from instruction 0 by the checker withphis (coversEntry, a closed Boolean), andchainsa list of sequences of loops (LoopChain, MojoProof/Sym/Loop.lean), each starting atfn's first block, whose paths the checker withphis accepts: the path into the first loop from instruction 0, each loop's round with its nested loops, and each path out (coversChains, a closed Boolean). Suppose the caller's pointer bytes name known numbers (m.BytesIn m.Known), the start succeeds on every admitted address choice and oracle, the observation reads only blocks, and for every admitted choice and oracle, withg,cthe start's grid and contexts, there is an invariantPwith:P 0 g.mem; for every threadkwith framefand every memorym'ofP k, withV = Valuation.entry (c k) 0 m' f, either some path ofpathsis aRetfromVtoP (k + 1), or some sequenceCofchainsruns fromVthrough its loops toretwith a memory ofP (k + 1)(RetLs (P (k + 1)) C.loops V C.l C.ds C.S C.E: for each loop an invariant indexed by the round and a trip count,ChainWith.loop); and every memory ofP N(Nthe number of threads) has a trace with no data race that keeps the promise of!invariant.load, and an observationywithR y. ThenKernel.Sound prog fn L args m adm obs R.Kernel.sound_of_pathsis the casechains = [], whose second disjunct is false: the same conclusion fromcoversEntryand aRetalong some path ofpathsfor every thread.Kernel.sound_of_chainsWithis the theorem for every flagcontract: the checks arecoversEntryWith contractandcoversChainsWith contract(withfmul contractin the path checker whencontract,coversPathWith), and each thread's run is aRetWith contractalong a path or aRetLsWith contractthrough a sequence of loops, in which afadd contractreads the operands of a recordedfmul contractand fuses them or not by the thread's oracle.Kernel.sound_of_chainsis its casecontract = false.- The elementwise invariant
Elem m₀ out w cell bs k m: blockoutofmis blockoutofm₀after threadsi < kin turn wrotebs iatcell i(nothing whenbs i = none), every other block ism₀'s, and every access ofm's trace is owned (Elem.Own: one tooutlies in its thread's cell ofwbytes, one elsewhere reads and is not anatomicrmw's, no!invariant.loadreadsout).Elem.zero: a memory with an empty trace is ofElem … 0from itself.Elem.succ: a memory whose blockoutadds threadk's write, whose other blocks are unchanged and whose new accesses are owned, is ofElem … (k + 1).Elem.safe: if the cells arewapart, the trace of every memory ofElemhas no data race and keeps the promise of!invariant.load(the core'skeptatsig, at every launch). Kernel.sound_eval.Ret.check V psis a Boolean (WalkWith falsedecided, theretexit decided, the last block's effects.ok),Ret.out V d psthe memory those effects leave (dif none), andRet.of_check:Ret.check V ps = true → Ret V (· = Ret.out V d ps) ps.Ret.pick V pathsis the first path thatRet.checkaccepts.Kernel.mems g c paths kis the memory threads0tok - 1leave in turn, each along its picked path from the memory before it, andKernel.check g c pathssays that every thread's picked path is accepted. IfcoversEntryholds, the caller's pointer bytes are known, the start at choicechand oracleωis.ok (g, c), the observation reads only blocks,Kernel.check g c paths = true, and the memoryKernel.mems g c paths Nhas a trace with no data race that keeps the promise of!invariant.loadand an observationywithR y, thenKernel.Sound prog fn L args m (fun ch' ω' => ch' = ch ∧ ω' = ω) obs R.Kernel.sound_elem. Fix an oracleω, an output blockout, cellscellthat arewapart (Apart cell w) and bytesbs. IfcoversEntryholds, the caller's pointer bytes are known, the start succeeds at every address choice andω, and on every start(g, c)every threadk, from every memory ofElem g.mem out w cell bs kand with its one framef, takes some path ofpathsthat is aRettoElem g.mem out w cell bs (k + 1), thenKernel.Sound prog fn L args m (fun _ ω' => ω' = ω) (fun m => some m.blocks) (Elem.Out m out cell bs N)withN = volume L.grid * volume L.block: blockoutof the final memory is blockoutofmwith the bytes of threads0toN - 1put in turn, and every other block ofmis unchanged.Kernel.sound_mapN: letfn's parameters beps ++ [pc], the one at each positionjnamed%j, every one ofpsbyvalof a struct typeTwith a codec for.agg [.ptr p, z](alignmental'dividingT's and the generic space's) andpcnotbyvalwithwithAttrstaking the count argumentvtouon every memory (any type and width); letblbe block numbers, one for each ofps,m's pointer bytes be known,mhave blockoowned by all threads, the start onbl.map (fun a => .agg [.ptr ⟨a, 0⟩, z]) ++ [v]succeed at every choice andω, andcellbewapart. If for every threadk < N, context withprog,L.env k, identity⟨k, k / volume L.block⟩and oracleω k, memorym₀withm's blocko, memorym'withElem m₀ o w cell bs k m'on which every block ofmbutois unchanged, and framefoffnwhose%i, for each positioniofbl, points to offset 0 of a block other thanofrom whichTloads at alignmental'as the struct ofbl[i], and whose%n(nthe length ofbl) isu, some path ofpathsis aRettoElem m₀ o w cell bs (k + 1), then the conclusion ofKernel.sound_elemholds on those arguments without = o. It isKernel.sound_mapNWith(11) withoutfmul contract, with no loops, the one scalar(pc, v, u),Severy thread and the admission ofωalone.Kernel.sound_map2, its casebl = [a, b, o]with ani32count: letfn's parameters be[p0, p1, p2, p3]named%0to%3,p0top2byvalof a struct typeTwith a codec for.agg [.ptr p, z](alignmental'dividingT's and the generic space's),p3notbyvalwithwithAttrspassing.bits 32 nas it is; letmmeetMap2.Pre l t enc al z m a b o n x y(l = prog.layout), the start onMap2.args z a b o nsucceed at every choice andω, andcellbewapart. If for every threadk < N, context withprog,L.env k, identity⟨k, k / volume L.block⟩and oracleω k, memoriesm₀,m'withElem m₀ o w cell bs k m', and framefoffnwhose%0to%2point to offset 0 of blocksq0toq2other thanofrom whichTloads at alignmental'as the structs ofa,b,o, whose%3isn, and on whose memorym'the buffer, tensor andMem.Fitsfacts ofMap2.Prehold, some path ofpathsis aRettoElem m₀ o w cell bs (k + 1), then the conclusion ofKernel.sound_elemholds withargs = Map2.args z a b o nandout = o.Kernel.sound_map2Withis the same for each flagcontract, withcoversEntryWith contractand aRetWith contractper thread;Kernel.sound_map2is it atfalse.RetWith.exists_true_of_ret(MojoProof/Sym/RetFlag.lean): for every valuation, predicate and list of paths none of whose summaries records anfmul contractproduct (pathNoProds, aBool), some path is aRetWith truewhen some path is aRet.vadd.retandvadd.correct(MojoProof/Kernels/Vadd.lean), about the one kernelvector_addition. Assume a valid launch whose grid and block have side 1 inyandz,4 ∣ al, distincta,b,out,n ≤ Nandn < 2 ^ 31.vadd.ret: for a threadkof the launch whose context hasvadd.prog,L.env k, identity⟨k, k / volume L.block⟩and oracleω k, a frame offn_0whose%0to%2point to offset 0 of blocksp0top2other thanoutthat hold the structs ofa,b,out, and whose%3isn, and a memory ofElem m₀ out 4 (4 * ·) (vadd.bytes ω x y n) kon whicha,b,outare buffers of at leastnfloats that fit anda,bholdx,y: some path ofvadd.pathsis aRetto the same invariant atk + 1.vadd.correct: for a caller's memory ofMap2.Pre(MojoProof/Sem/Precond.lean, tailvadd.argTail: closed for the arguments, the buffer and tensor facts above,n ≤ N,n < 2 ^ 31, the three buffers fit),vector_additionis sound as in 6 withbs = vadd.bytes ω x y nand cells4 i.- The start facts (MojoProof/Sym/Start.lean and MojoProof/Sym/Kernel.lean), for every
program, kernel, launch, arguments, memory, address choice
chand oracle withGrid.start … = .ok (g, c), threadk < g.threads.sizewith frame[f], and positioniwith parameterpand argumentv, wherep's namernames no parameter beforei:launchArgs_byval: every valuewat positioniof whatlaunchArgsreturns isLaunchArg … i p v win the memory it returns (for abyval(T)parameter,wpoints to offset 0 of a blockbyvalBlockholdingT's encoding ofv, owned by the thread; otherwisewithAttrsgiveswon some memory).Thread.start_regs: registerrof the start's frame holds the argument ati.Grid.start_arg: their composition ing.mem.Grid.start_buffer: ifpisbyval(T),v = enc xfor a codecencofTandaldividesT's alignment and2 ^ w, thenf.regs rpoints to offset 0 of a blockqofg.memowned by threadkfrom whichTloads asenc xat alignmental.Grid.start_scalar: ifpis notbyvalandwithAttrsgiveswon every memory,f.regs r = some w. -
The corollaries of a binary float map (MojoProof/Sym/Kernel.lean, section
Map2), for every program, kernel, launch, arguments, memorymwith a blockout, layoutl, float typeft, operationop, oracle numberso, tensorsx,yof lengthN, countn, and cellsl.stored (.fp ft)bytes apart.Elem.map2 l ft op o x y n kis the encoding ofdeliver (op x_k y_k) (o k)ifk < nandk < N, elsenone(Kernels.vadd.bytes ωandKernels.vmul.bytes ωare it atModel.add,Model.mulando k = ω k (Nat.pair 23 0) / 3).Elem.word l ft out cell B kis the float that cellcell kof blockoutofBdecodes to.Kernel.Obs … obs ch ω y: the start atchandωsucceeds and some schedule reaches from its grid a grid where every thread has returned, whose memoryobsmaps toy. WriteS o TforKernel.Soundfor the observation of the blocks andElem.Out m out cell (Elem.map2 l ft op o x y n) T.Kernel.Sound.map(MojoProof/Sem/Replay.lean) atf := some:Kernel.SoundforRgives it for every weakerR'.Kernel.Sound.obs:Rholds of everyKernel.Obsat an admitted choice and oracle.Elem.Out.map2_word: blocks ofElem.OutafterMthreads forElem.map2's bytes hold at the cell of every threadkbelown,NandMthe floatdeliver (op x_k y_k) (o k).Kernel.map2_min:S o Tat an admission givesKernel.Soundat it forElem.Outaftermin n Tthreads, so after thenthreads below the count whenn ≤ T(Elem.Out.min: when threads fromnon put nothing,Elem.OutafterTthreads isElem.Outaftermin n T).Kernel.map2_real: fromS o Tat an admission, at every admitted choice and oracle every observationBof a complete run has a floatvat the cell of every threadkbelown,NandT, and ifvis finite thenv = op x_k y_k.Kernel.map2_finEq: ifS (o ω) Tholds for every oracleωat the admissionfun _ ω' => ω' = ω, then at any two choices and oracles the observationsB,B'of complete runs have floatsv,v'at the cell of every suchk, withFinEq v v'.Kernel.map2_finEqwithFinEq.eq_of_isFinite(a wordFinEqto a finite word is equal to it): underKernel.map2_finEq's premise, a finite float at the cell of such akin one observation is the float there in every observation, at every choice and oracle.
The instances (MojoProofTest/Kernel.lean) take
SfromKernels.vadd.correctandKernels.vmul.correct, for every valid launch ofTthreads whose grid and block have side 1 inyandz,4 ∣ al, memory ofMap2.Pre, choice and oracle:vadd_min,vadd_real,vadd_finEq,vadd_stableand the fourvmul_*.vadd_realalso states thatop x_k y_kis TorchLean's(x + y)atkand that its real value is the real sum rounded to binary32 (Model.roundAt);vmul_realstates that it is TorchLean's(x * y)atkand that its real value is the real product rounded to binary32. -
Checking
Elem.Outby evaluation, and refuting the canaries (MojoProof/Sym/Kernel.lean).Elem.outBelow m out cell bs N nb K Bis a Boolean: every blockb < nbthatmhas is a block ofBthat agrees (Elem.agree: every field, and the bytes at the offsets belowK) withElem.put cell bs Nofm's block atoutand withm's block elsewhere.Elem.Out.outBelow:Elem.Out m out cell bs N Bimplies it, for everynbandK.Elem.Out.of_outBelow, the converse: for everym,out,cell,bs,N,nb,KandB, ifBpasses the check,mhas no block fromnbon, every threadi < Nwith byteslhascell i + l.length ≤ K, and every blockxofmandB's blockyat its number havey.bytes i = x.bytes ifor everyi ≥ K, thenElem.Out m out cell bs N B.Elem.Out.of_run: for every program, kernel, launch, arguments, memorym, choice and oracle whose start gives(g, c), and gridzthatgreaches (Grid.Step), ifz's blocks passElem.outBelow m out cell bs N nb K,mhas no block fromnbon, every threadi < Nwith byteslhascell i + l.length ≤ K, and every block ofmis owned by no thread and has at mostKbytes, thenElem.Out m out cell bs N z.mem.blocks.Elem.canaries l t enc x bs nis the list of the five byte functions that Sem/Replay.lean's probes make frombs:Probe.drop 0 bs(cell 0 omitted),Probe.stale(no thread stores),Probe.swap 0 1 bs(cells 0 and 1 swapped),Probe.zero (l.stored t) n(cells belownzero) andProbe.copy l t enc x n(cells belownhold the inputx's cells underenc).Kernel.replay_canaries: for every program, kernel, launch, arguments, memorymwith a blockout, choicech, oracleω, fuel, phases, cells,Tand canaries: if for each canarybs'the replay (Kernel.replay) with the observation of blockout's bytes (Replay.bytes?) and the predicate "equal to the bytes ofElem.put cell bs' Tofm's blockout" isbad, then for each canarybs'and every admission that admitschandω, the kernel is notKernel.Soundfor the observation of the blocks andElem.Out m out cell bs' T. -
Elementwise kernels with loops (MojoProof/Sym/Kernel.lean).
Elem.Only out S m: every access to blockoutonm's trace is by a thread ofS.Elem.Only.log: logging an access keeps it if, when the access is toout, its thread is inS.Elem.Only.apply: a block effect (SEff.apply) that succeeds at a valuation whose thread is inSkeeps it.Elem.safe_on: every memory ofElem m₀ out w cell bs kandElem.Only out Swhose cells arewapart onS(Apart (fun i : {i // S i} => cell i) w; the cells of other threads may overlap them) has a trace with no data race that keeps the promise of!invariant.load.Kernel.sound_cells: for every program, kernel, launch, arguments, admissionadm, paths, sequences of loops, output blockout, cells, bytes and setS, letcoversEntryandcoversChainshold, the caller's pointer bytes be known, the start succeed on every admitted choice and oracle, and the cells bewapart onS. If on every admitted start(g, c)every threadkwith framef, from every memorym'ofElem g.mem out w cell bs kandElem.Only out S, withV = Valuation.entry (c k) 0 m' f, either takes some path ofpathsthat is aRetfromV, or runs some sequence ofchainsfromVtoret(RetLs), to a memory ofElem g.mem out w cell bs (k + 1)andElem.Only out S, thenKernel.Sound prog fn L args m adm (fun m => some m.blocks) (Elem.Out m out cell bs N).Kernel.sound_elem(6) is its case with no loops,Severy thread and one oracle.Kernel.sound_cellsWithis the theorem for every flagcontract(coversEntryWith,coversChainsWith,RetWithandRetLsWithatcontract, as in 3);Kernel.sound_cellsis its casecontract = false.Kernel.sound_mapNWith: for every flagcontract, letfn's parameters beps ++the parameters of a listscof scalars (each a parameter, its argument and the valuewithAttrstakes the argument to on every memory), the one at each positionjnamed%j, every one ofpsbyvalof a struct typeTwith a codec for.agg [.ptr p, z](alignmental'dividingT's and the generic space's) and none ofsc'sbyval; letblbe block numbers, one for each ofps,m's pointer bytes be known,mhave blockoowned by all threads, the start onbl.map (fun a => .agg [.ptr ⟨a, 0⟩, z]) ++ sc.map (·.2.1)succeed on every admitted choice and oracle, and the cells bewapart onS. If for every admitted choice and oracle, threadk < N, context withprog,L.env k, identity⟨k, k / volume L.block⟩and oracleoracle k, memorym₀withm's blocko, memorym'ofElem m₀ o w cell bs kandElem.Only o Son which every block ofmbutois unchanged, and framefoffnwhose%i, for each positioniofbl, points to offset 0 of a block other thanofrom whichTloads at alignmental'as the struct ofbl[i], and whose%(n + j)(nthe length ofbl) issc[j]'s value, either some path ofpathsis aRetWith contractor some sequence ofchainsruns toret(RetLsWith contract), to a memory ofElem m₀ o w cell bs (k + 1)andElem.Only o S, thenKernel.Sound prog fn L (bl.map (fun a => .agg [.ptr ⟨a, 0⟩, z]) ++ sc.map (·.2.1)) m adm (fun m => some m.blocks) (Elem.Out m o cell bs N).Launch.apart_xy: for every valid launchLwith side 1 inz, row strides, boundsmandn ≤ sand widthw, the cells(L.index k .x * s + L.index k .y) * warewapart on the threadsk < NwithL.index k .x < mandL.index k .y < n. - The start's facts as premises (MojoProof/Sym/Kernel.lean).
Kernel.sound_entry: for every program, kernelfn, launch, argumentsargs, memorym, admission, observationobs, predicateR, paths and sequences of loops, letcoversEntryandcoversChainshold, the caller's pointer bytes be known, the start succeed on every admitted choice and oracle, andobsread only blocks. LetIbe a predicate on the number of threads done and a memory such thatI 0holds of every memory that has every block ofmand an empty trace; for every threadk < Nand valuationVwhose context has the programprog, the identity⟨k, k / volume L.block⟩and the special registersL.env k, whose function isfn, whose registerrholdswfor every positioniwith parameterpnamedr(named by no earlier parameter, notbyval), argumentvandwithAttrstakingvtowon every memory, and whose memory is one ofI k, either some path ofpathsis aRetfromVtoI (k + 1)or some sequence ofchainsruns fromVtoretwith a memory ofI (k + 1)(RetLs); and let every memory ofI Nhave a trace with no data race that keeps the promise of!invariant.loadand an observationywithR y. ThenKernel.Sound prog fn L args m adm obs R.Kernel.sound_entryWithis the theorem for every flagcontract(as in 3), withIalso indexed by the start's memorym₀(I m₀ 0 m₀for everym₀that hasm's blocks and an empty trace, the per-thread premise for every admitted choice and oracle and everym₀that hasm's blocks, from a memory ofI m₀ ktoI m₀ (k + 1), and the end onI m₀ Nfor everym₀) and two more facts onV: its oracle isoracle k, and the registerrof everybyval(t)parameter namedr(by no earlier parameter) whose argument isenc xfor a codecencoftpoints to offset 0 of a block ofm₀owned by threadkfrom whichtloads asenc xat every alignment dividingt's and the generic space's.Kernel.sound_entryis its casecontract = falsewithInot depending onm₀.n.sound_loop, whichmojo_kernelgenerates with theloopclause whenfnis a constant and the program has no globals: for every launch, block numbers and scalars of the clauses, memorymclosed forn.args(Mem.Closed) whose pointer bytes are known, admission, observation reading only blocks, predicateRand invariantIas above, if each thread'sVwith the facts above (the registers of thescalarsandpointersparameters holding their arguments as hypotheses) and a memory ofI kmeets the first clause's preconditionpre V, with every memory ofpost Vone ofI (k + 1), andI Ngives the trace and observation facts, then the kernel onn.argsisKernel.Sound. - Matmul kernels (MojoProof/Sym/KernelMat.lean).
Kernel.sound_mat: for every flagcontract, programprog, kernelfnwhose parameters arep0top5, the one at each positionjnamed%j,p0top2byvalof a struct typeTwith a codec for.agg [.ptr p, z](alignmental'dividingT's and the generic space's) andp3top5notbyval, whose attributes keep thei32words ofm,nandKon every memory, valid launchLwith side 1 inz, paths and sequences of loops withcoversEntryWith contractandcoversChainsWith contract, element typetwith encoderenc, alignmental, blockso,a,b, row stridessA,sB,sCwithn ≤ sC, tensorsx(m × sA) andy(n × sB), and memorymemclosed forMat.args z o a b m n Kwitha ≠ o,b ≠ o, the threeMem.Buffers,Mem.Holdsofxandyand the threeMem.FitsofMat.Pre, let the start onMat.args z o a b m n Ksucceed on every admitted choice and oracle, and letS k := k < N ∧ L.index k .x < m ∧ L.index k .y < nandcell k := (L.index k .x * sC + L.index k .y) * w. If for every admitted choice and oracle, threadk < N, context withprog,L.env k, identity⟨k, k / volume L.block⟩and oracleoracle k, memoriesm₀andm', and framefoffnwhose%0to%2point to offset 0 of blocks other thanofrom whichTloads at alignmental'as the structs ofo,a,b, and whose%3to%5are the words ofm,n,K, on whichm'has the buffers ofmem(aandbholdingxandy), fromElem m₀ o w cell bs kandElem.Only o S, a thread ofSruns some sequence ofchainstoret(Hin,RetLsWith contract) and a thread not ofStakes some path ofpaths(Hout,RetWith contract), to a memory ofElem m₀ o w cell bs (k + 1)andElem.Only o S, thenKernel.Sound prog fn L (Mat.args z o a b m n K) mem adm (fun m => some m.blocks) (Elem.Out mem o cell bs N).
Proofs
Runs.of_retisRuns.of_retWith(MojoProof/Sym/Loop.lean) atcontract = false. There: if the path is empty,Retis false. Otherwise the path is a chain with no loop, andRuns.of_chainWithruns it to its end. Its last block is taken there byBlock.sound_retWithatcontract = false: the thread's steps reach the last block's end on the memoryme'that the last block's effects make, and the next step is.doneoff.allocas.foldl (setLive · false) me'. The effects' result is.ok me'and.ok me, some' = me, and the fold over the empty list ofallocablocks isme. Steps followed by that step isRunsby definition.- By
Grid.start_run, entrykof the start's thread array is.run twithThread.start fn as = .ok tfor some argumentsas.Thread.startfails whenfnhas no block, and otherwise returns exactly the one-frame thread at the first block's label, instruction 0, noallocablocks and step count 0.Grid.threadreadstback. - Fix an admitted choice and oracle. The start succeeds, with
gandc; takePfrom the premise.Seq.start_sound_invneedsP 0 g.mem, the trace and observation facts onP N(premises), and, for each threadk < Nand memorym'ofP k, a run to its end leaving a memory ofP (k + 1). For that run: by 2, threadkis⟨[f], 0⟩withfat the entry; the premise gives a path ofpathsthat is aRetfromValuation.entry (c k) 0 m' f; bycoversEntrythe path starts at the entry's label and is accepted from instruction 0; the context's program isprog(Grid.start_ctx); so 1 gives the run andP (k + 1). In the second case,Runs.of_chainsWith(MojoProof/Sym/Loop.lean) gives the run andP (k + 1)fromcoversChains, the same frame facts and theRetLs:coversChainssays thatCstarts at the entry's label and that its paths are accepted,ChainWith.reachtakes the thread through the loops to the last path,Block.sound_retWithtakes it to its end, and the frame has noallocablocks, so the memory left is theRetLs's. The conclusionGrid.Sound L c g obs Rwith the start's equation isKernel.Soundat this choice.Kernel.sound_of_paths: the theorem atchains = [](coversChainsof no sequence istrueby evaluation), each thread's premise the first disjunct. The theorem proved this way isKernel.sound_of_chainsWith, at every flag, withRuns.of_retWithfor a path andRuns.of_chainsWithfor a sequence of loops (MojoProof/Sym/Loop.lean;Block.sound_retWithfor the last block, MojoProof/Sym/Path.lean).Kernel.sound_of_chainsis it atfalse:coversEntryWith falseiscoversEntryandRetWith falseisRetandRetLsisRetLsWith falseby definition. - Zero: the fold over
range 0is the identity (so blockoutis(m₀.blocks out).map id), and an empty trace has no access. Successor:range (k + 1)isrange kfollowed byk, so the fold fork + 1is threadk's write after the fold fork; old accesses were owned and new ones are owned by premise. Safety:Elem.safeisElem.safe_on(11) with every thread inS(Apart cell wcomposed with the injectiveSubtype.val;Elem.Onlyholds trivially). Ret.of_check: on a nonempty path the Boolean's three conjuncts giveWalkWith false, the exit, and an.ok meof the effects, andRet.outis thatme.Kernel.sound_eval: apply 3 with the admission's one choice and oracle (the start's equation is the premise) and the invariantP k m' := m' = Kernel.mems g c paths k.P 0isKernel.mems's first equation. For threadkwith framef,Kernel.check's conjunctksays thatRet.checkaccepts the picked path onKernel.mems … k, soRet.of_checkmakes it aRettoKernel.mems … (k + 1), which isRet.outof that path byKernel.mems's second equation at[f]; the picked path is inpathsbecausefind?returned it (it is notnone, sinceRet.checkrejects the empty path).P Nis the premises onKernel.mems … N.Kernel.sound_elemis 11 atchains = [](coversChainsof no sequence istruebyrfl),Severy thread (Apart cell wcomposed with the injectiveSubtype.valisAparton the subtype), the admissionfun _ ω' => ω' = ω, and each thread'sRettoElemraised to aRettoElemand the trivially trueElem.Only(Ret.mono), the first disjunct.Kernel.sound_mapN: applyKernel.sound_mapNWith(11) atcontract = false,chains = [],sc = [(pc, v, u)],Severy thread and the admissionfun _ ω' => ω' = ω; its scalar fact atj = 0is%n = u, and each thread'sRettoElemis raised to aRettoElemand the trivially trueElem.Only(Ret.mono), the first disjunct.Kernel.sound_map2With: applyKernel.sound_mapNWith(11) asKernel.sound_mapNdoes, atps = [p0, p1, p2],sc = [(p3, n, n)]andbl = [a, b, o], the pointer bytes byMem.Closed.bytesInfromMap2.Pre'sclosedando's owner from itsMem.Buffer; the names by cases on the position. For a thread, the three positions giveq0toq2; the facts ofaandbmove frommtom'since each reads only its block (Mem.Buffer.of_block,Mem.Fits.of_block,Mem.Holds.of_block), and those ofomove tom₀and then byElem.bufferandElem.fits. Then the premise applies, and itsRetWithis raised as inKernel.sound_mapN.Kernel.sound_map2isKernel.sound_map2Withatcontract = false(RetisRetWith falseandcoversEntryiscoversEntryWith falseby definition).RetWith.exists_true_of_ret: a summary withSummary.noProds(no register entry withSVal.factors) leaves the same products with or without the flag (prodsWith_noProds: with the flag a set register's product is the bind of its factors,none), soafterWith,intoWith,WalkWith,lastWithandRetWithagree along the path (RetWith.true_eq, by induction on the path).vadd.ret, generated bymojo_kernel'smap2clause (MojoProof/Sym/KernelCmd.lean, item 6): the tacticmojo_ret(MojoProof/Sym/Ops.lean, docs/tactics.md; not reproved here). No path is proved before a case split, so it splits on the branch condition neither side of whichomegadecides,k < n(the indexctaid * ntid + tidiskon a one-dimensional launch,Launch.index_oneDim). On each side it takes the path the branch selects, path 0 (%4 → %21 → %31) fork < nand path 1 (%4 → %30 → %31) otherwise, and proves its premises (WalkWith false, mojo_obl's walk, docs/proofs/obl.md) and each block's effects as steps ofElemwith the node values asmojo_valsproves them: block%4's three loads from the structs' blocksp0top2, notout(Elem.apply_load); on path 1 no effect, andbs k = nonefork ≥ n(Elem.skip); on path 0 block%21's loads ofx_kandy_kfromaandband its store of the encoding ofdeliver (x_k + y_k)at⟨out, 4 k⟩, threadk's bytes (Elem.apply_store); the blocks before the last byElem.intoWith(MojoProof/Sym/Ops.lean,Valuation.intoWith_mem), the last byElem.retWith.vadd.correct, generated by the same clause:Kernel.sound_map2(6) atvadd.covers,vadd.startsand cells4 i, which are 4 apart (apart_mul, fromapart_strideat base 0), withT = vadd.argTy,z = vadd.argTail, the codecLayout.Codec.ptrArgat alignment 8, the parameters' names,byvaltypes andwithAttrsbyrfl; its per-thread premise isvadd.ret.launchArgsis afoldlMover(fn.params.zip args).zipIdx;foldlM_zipIdx_invproves an invariantP iof the accumulator from one step at each position. The invariant: the list has lengthiand each entryj < iis itsLaunchArgin the current memory. Abyvalstep allocates blocknext(Mem.allocNext, which fails ifnextis taken), so the blocks before are unchanged (LaunchArg.mono) and the new entry is the pointer to it, whose block isbyvalBlockby the definition ofMem.alloc; another step keeps the memory.Thread.startsets the registers by the first parameter of each name (find?over the zip), so with no earlier parameter of namer, induction on the parameters gives the argument ati.Grid.start_arg:Grid.start_argsgives threadk'slaunchArgsandThread.start, and the blocks of the arguments' memory are blocks ofg.mem.Mem.load_byval: the block's address in the generic space isch (2 i) * align % 2 ^ w, whichaldivides; the check passes (owner threadk, offset 0,T's stored size within its size), and the bytes read are the encoding (read_alloc,Layout.encode_length), which decodes toenc xby the codec's round trip.Kernel.Sound.obs: the admittedKernel.Soundgives the start's gridgandGrid.Soundofg;Kernel.Obs's start is the same (the start is a function), sopostapplies to its done grid.Elem.Out.map2_word:Elem.Out's first field gives blockoutofBasElem.put cell bs Mofm's block; every encoding isl.stored (.fp ft)bytes long and decodes back (Elem.encode_float, fromLayout.Codec.float's round trip), soElem.put_read(by induction onM: a put at cellkis read back,Block.read_put_self, a put by another thread with bytes, at a cellwapart, is not seen,Block.read_put_apart, and a thread without bytes puts nothing), withApart cellrestricted to the threads with bytes (Subtype.val_injective), reads threadk's encoding at cellk, which decodes to its float.Kernel.map2_min:Elem.map2isnonefromnon (Elem.map2_none), soElem.put_of_none(induction onT - nwithElem.put_succ) givesElem.Out.min, andKernel.Sound.mapatf := somelifts it.Kernel.map2_real:Kernel.Sound.obsthenElem.Out.map2_wordgivev = deliver r (o k)withr = op x_k y_k; ifvis finite,ris not a NaN (a NaN is delivered as a NaN,isNaN_deliver, which is not finite), anddeliverreturns a non-NaN unchanged (deliver_of_isNaN_eq_false).Kernel.map2_finEq: the same at each oracle, with its own admissionω' = ωmet byrfl, givesdeliver r (o ω k)anddeliver r (o ω' k), which areFinEq(FinEq.deliverfromr = r). WithFinEq.eq_of_isFinite: asKernel.map2_finEq, and the finitedeliver r (o ω k)makesrnot a NaN, so both arer. The instances:Kernels.vadd.bytes ωisElem.map2atModel.addby definition,outis a block ofmbyMap2.Pre's buffer field, the cells4 iare 4 apart (apart_mul) andl.stored (.fp .float) = 4byrfl;vadd_realadds TorchLean'sTensor.add_applyand FloatLib'sModel.toReal_add_eq_roundAt(binary32 is IEEE, byrfl),vmul_realadds TorchLean'sTensor.mul_applyand FloatLib'sModel.toReal_mul_eq_roundAt.-
Elem.Out.outBelow: for each blockbbelownb, ifmhas none the check istrue; otherwiseElem.Out's first field (atout) or second field (elsewhere) givesB bas the block the check compares with, and every block agrees with itself (Elem.agree_self).Elem.Out.of_outBelow: a blockxofmis at a number belownb, so the check gives a blockyofBthere thatElem.agree Kaccepts againstElem.put cell bs N x(atout) orx. FromKon,y's bytes arex's by the last premise, and so are those ofElem.put cell bs N x(Elem.put_above, by induction onN: each put ends byK). Two blocks that agree on every field, on the bytes belowKand on the bytes fromKon are equal (Elem.agree_eq), which givesElem.Out's two fields.Elem.Out.of_run:Elem.Out.of_outBelow, whose last premise isGrid.start_reach_above(MojoProof/Sem/Writes.lean): a blockxofmis a block ofg.mem(Grid.start_blocks) owned by no thread, sozhas a block at its number with the same bytes fromx.sizeon, andK ≥ x.size.Kernel.replay_canaries: for a canarybs',List.allgives its replay'sbad, andKernel.replay_block(MojoProof/Sem/Replay.lean) atf = Elem.put cell bs' Trefutes the relation, whose blockoutisfofm's byElem.Out's first field;Kernel.replay_blockisKernel.replay_soundfor the observation of blockout's bytes, to whichKernel.Sound.mapcarries the observation of the blocks. -
Elem.Only.log: the new event is the access, which is tooutonly with its thread inS; the others arem's.Elem.Only.apply: by cases on the effect; a load or a store that succeeds logs one access byV's thread (for a store, throughMem.store_inv, MojoProof/Sem/Confluence.lean), soElem.Only.log; a failing effect gives no memory.Elem.safe_on: lettsbe the list of the threads of the accesses toouton the trace (afilterMap), all inSbyElem.Only, andKa number abovecell i + wfor everyiofts(induction onts). Applyracy_kept_of_cellsto the cellscell ifori ∈ tsandK + w * iotherwise. They arewapart: two oftsby the premise onS; one oftsand one not sinceK + w * j ≥ K ≥ cell i + w; two not oftsbyapart_mul. An access tooutis by a thread ofts, so it lies in that thread's cell (Elem.Own); the other two conjuncts areElem.Own's.Kernel.sound_cells: apply 3 with the invariantP k me := Elem g.mem out w cell bs k me ∧ Elem.Only out S me.P 0 g.memisElem.zeroon the start's empty trace (Grid.start_trace), on whichElem.Onlyholds vacuously; the per-thread premise is the hypothesis. OnP N,Elem.safe_ongives the trace facts, and the observationsome m'.blocksmeetsElem.Out: blockoutofm'is blockoutofg.memwith the puts (Elem.cells), which is blockoutofm(Grid.start_blocks) after the puts of theg.threads.size = Nthreads (Grid.start_args); every other block isg.mem's (Elem.rest), hencem's. The theorem proved this way isKernel.sound_cellsWith, throughKernel.sound_of_chainsWith(3);Kernel.sound_cellsis it atfalse(the premise as it is, by definition).Kernel.sound_mapNWith: applyKernel.sound_cellsWith. For a threadkwith framefon a memorym'ofElem kandElem.Only:f.fn = fn(Grid.start_thread),kis below the thread count (Grid.start_args), the context facts areGrid.start_ctx. For each positioniofbl, parameteriisps[i]and argumentiis the struct ofbl[i](List.getElem?_append_left,List.getElem?_map); no earlier parameter is named%i, since parameterjis named%j(take_names); so register%ipoints to a blockqofg.memowned by threadkfrom whichTloads as the struct (8,Grid.start_bufferwith the codec).qis noto, whichg.memhas withm's owner.all(Grid.start_blocks), so the struct load moves fromg.memtom'(Elem.load). For each positionjofsc, parameter and argumentn + jaresc[j]'s (List.getElem?_append_right), so%(n + j)holds its value (Grid.start_scalar). The blocks ofmother thanoare blocks ofg.mem(Grid.start_blocks) and ofm'(Elem.rest; togetherElem.start_block). Then the premise applies atm₀ = g.mem.Launch.apart_xy:Launch.cell_apart(MojoProof/Sem/Index.lean) on the threads of the subtype, at base 0 and widthw, for two threads whose values differ (Subtype.ext). Kernel.sound_entry: apply 3 withP := Iat each admitted start(g, c).P 0 g.mem:g.memhas every block ofm(Grid.start_blocks) and an empty trace (Grid.start_trace). For a threadk < g.threads.sizewith framefand memorym'ofI k:g.threads.size = N(Grid.start_args); the thread is⟨[f'], 0⟩withf'.fn = fn(Grid.start_thread), sof' = f; the entry valuation's context has the program, identity and special registers (Grid.start_ctx), its function isf.fn = fn, its registers aref.regs, which hold the arguments (Grid.start_scalar, 8), and its memory ism'; the premise gives the disjunct. OnP N, the premise onI N.n.sound_loop:mojo_kernelelaboratesKernel.sound_entryatn.covers,n.coversChains, the pointer bytes and the start byn.startsfromMem.Closed; the per-thread premise applies the clause's hypothesis to the register facts thatKernel.sound_entryprovides (for eachscalarsorpointersparameter, its position, name, argument and attributes byrflon the concrete function andn.args;withAttrsof a value with norange,nonnulloralignattribute returns it, byrfl), thenn.looponpre Vandpost V, the second disjunct. The theorem proved this way isKernel.sound_entryWith, throughKernel.sound_of_chainsWith(3) withP := I g.mem, the oracle byGrid.start_ctxand eachbyvalparameter's register byGrid.start_buffer(8) at the framef;Kernel.sound_entryis it atfalsewithIconstant inm₀(each thread's premise as it is, by definition).Kernel.sound_mat: applyKernel.sound_mapNWith(11) at the structs[p0, p1, p2]of the blocks[o, a, b], the scalarsp3,p4,p5with the words ofm,n,K, andSandcellas in 13 of the statements. Its parameter,byval, codec andwithAttrspremises are the hypotheses (by cases on the three members of each list);Mem.BytesInisMem.Closed.bytesIn;ois owned by all threads by itsMem.Buffer; the cells are apart onSbyLaunch.apart_xywithn ≤ sC. For a thread with the facts of 11: registers%0to%2and the struct loads are its first premise at positions 0, 1 and 2, and%3to%5its second;aandbare blocks ofmemother thano, so unchanged onm', and theirMem.Buffer,Mem.FitsandMem.Holdsmove tom'(Mem.Buffer.of_block,Mem.Fits.of_block,Mem.Holds.of_block);o's come fromm₀'s throughElem(Elem.buffer,Elem.fits). By cases onS k,Hingives the second disjunct andHoutthe first.
Dependencies
Block.sound_retWith, coversPathWith, WalkWith, Valuation.entry, Valuation.into,
Valuation.lastWith (Sym/Rel.lean, Sym/Path.lean);
SEff.run, vals (Sym/Term.lean); Runs, Grid.thread, Seq.start_sound_inv
(Sym/Sched.lean); LoopChain, ChainWith, RetLs, coversChains, Runs.of_chainsWith, and
for the loop instance ChainWith.of_rounds, EdgeWith.dec, RoundWith.dec (Sym/Loop.lean);
Grid.start_run (Sem/Closed.lean); Grid.start_ctx (Sem/Grid.lean); Thread.start
(Sem/Thread.lean); racy_kept_of_cells, Apart (Sem/Trace.lean, Sem/Buffer.lean).
For 6 and 7 also: Grid.start_blocks (Sem/Grid.lean), Grid.start_trace
(Sem/ScheduleOwned.lean); Grid.start_args (Sym/Start.lean), Grid.start_ctx (Sem/Grid.lean);
Launch.sreg_bound (Sem/Spec.lean); SNode.eval_sreg (Sym/OblLemmas.lean); Launch.index_ops,
Launch.index_oneDim, intCast_trunc_sext (Sem/Index.lean); apart_stride (Sem/Buffer.lean);
gep_buffer, load_buffer, SVal.eval_reg, SVal.eval_node (Sym/OblLemmas.lean);
floatBin_ofFloat (Sem/FloatRel.lean). For 7 and 8: Map2.Pre, Mem.Fits,
Layout.Codec.ptrArg (Sem/Precond.lean); launchArgs, Mem.allocNext, withAttrs
(Sem/Thread.lean); Mem.check_ok, Mem.load_of_check, read_alloc (Sem/Buffer.lean);
Mem.Closed.bytesIn (Sem/Closed.lean). For 9: deliver, deliver_of_isNaN_eq_false,
isNaN_deliver (Sem/Float.lean); FinEq, FinEq.deliver (Sem/FloatRel.lean);
Layout.Codec.float, Block.read_put_self, Block.read_put_apart (Sem/Buffer.lean); for the
instances FloatLib's Model.toReal_add_eq_roundAt, Model.toReal_mul_eq_roundAt and TorchLean's
Tensor.add_apply, Tensor.mul_apply. For 10: Kernel.replay, Kernel.replay_block,
Kernel.replay_sound, Kernel.Sound.map, Replay.bytes? and the probes Probe.drop,
Probe.stale, Probe.swap, Probe.zero, Probe.copy (Sem/Replay.lean). For 11 also:
Mem.store_inv (Sem/Confluence.lean); apart_mul (Sem/Buffer.lean, from apart_stride);
Ret.mono (Sym/Kernel.lean); for its instance kernelC ChainWith.of_rounds, ChainWith.last
(Sym/Loop.lean), Elem.apply_store, Elem.skip (Sym/Kernel.lean). For 12 also:
Grid.start_thread (2), Grid.start_scalar (8); for n.sound_loop's instance kernelK
Mem.Closed.alloc (Sem/Precond.lean). For the contract forms: coversPathWith, RetWith,
Block.sound_retWith (Sym/Path.lean); coversChainsWith, RetLsWith, ChainWith,
Runs.of_retWith, Runs.of_chainsWith (Sym/Loop.lean); summarizeC
(Sym/Checker.lean); for the instance kernelF the tactic kernel_check, mem_eta and
ret_storeWith (MojoProofTest/KernelCells.lean); for RetWith.exists_true_of_ret,
prodsWith (Sym/Block.lean), lookup_ne (Sym/Rel.lean), regProdIn, regProd (Sym/Checker.lean),
Valuation.afterWith, Valuation.intoWith, WalkWith and Valuation.lastWith
(Sym/Path.lean). For Launch.apart_xy: Launch.cell_apart
(Sem/Index.lean). For Elem.Out.of_run: Grid.start_reach_above (Sem/Writes.lean). For 13:
Mat.args, Mem.Buffer.of_block, Mem.Fits.of_block, Mem.Holds.of_block (Sem/Precond.lean),
Elem.buffer, Elem.fits (Sym/Kernel.lean) and Launch.apart_xy.
Scope
Kernel.sound_of_chains(3) holds for every program, kernel, launch, admitted address choice and oracle, list of paths and list of sequences of loops. It covers the kernels whose every thread runs in its own frame, with no barrier or other collective call (every grid step is a thread'sGrid.advance), either one path without a cycle from the entry toretor a sequence of loops (each with the loops nested in its rounds) from the entry toret. The per-threadRetorRetLson every memory of the invariant, with each loop's invariant and trip count, is the caller's premise.Kernel.sound_of_pathsis its case without loops.- Its loop instance (MojoProofTest/KernelLoop.lean) is one program and one launch:
cntK, the counting loop of MojoProofTest/SymLoop.lean (for i in [0, n): p[i] = i) with%nand%pas parameters, on one block of one thread withn = 3, the memoryoutC(one global writable block of threei64cells), address choicech₀and oracleω₀.kernelKis an instance ofloopK.sound_loop(12), whichmojo_kernelgenerates forcntKwith thescalarsclause for%n, thepointersclause for%pand the loop clause; the start's facts come fromoutC_closed(Mem.Closed), and its per-thread premise, the preconditionpreB, from the registers%nand%pthe generated premise provides andoutC's block in the thread's memory, with nothing of the start evaluated. The clause's obligations are closed byinvB_entry,invB_stepandinvB_exit, which hold for every function withcnt's blocks, every context whose program hascntP's layout, and every boundn ≤ 2 ^ 60, block and trace. Their invariantinvBis SymLoop'sinvN(stated forcntitself) with the stores of the rounds so far on the trace, so that the postcondition gives the end's trace. - The
loopclause ofmojo_kernel(docs/kernel.md) provesn.loopfrom its four obligations byChainWith.loopat the clause's invariant and trip count, withChainWith.lastfor each round and for the path out (Ret.monofrom the postcondition toQ), andn.sound_loopbyKernel.sound_entry(12, the second disjunct) andn.loop. Its instancecntk.loop(MojoProofTest/KernelCmd.lean) holds for every valuation ofcntPre, at every boundn ≤ 2 ^ 60;cntk_threeapplies it atstart 3.cntk.sound_loophas no instance:cnthas no parameters, so no start meetscntPre.loopK.sound_loop(MojoProofTest/KernelLoop.lean) is the one forcntK.n.sound_loopgives no register fact for abyvalbuffer parameter (the start copies it into a new block,Grid.start_buffer). With a clause for each of several loops in sequence,n.loopisChainWith.loopfor each loop in turn: the next loop's run starts at every valuation of the invariant at the trip count, by that loop's exit obligation (the next clause's precondition, and the next postcondition implies this one's), and the last loop's path out ends withChainWith.lastandRet.mono. Its instancecnt2k.loop(MojoProofTest/KernelLoop.lean) is SymLoop'scnt2from one valuation,V2(%n = 2);cnt2k_retLsapplies it there. With the flagcontractthe clause checks its loops withfmul contract(summarizeC), its obligations are overEdgeWith true,Valuation.roundWith true,RoundWith trueandRetWith true,n.loopis aRetLsWith truebyChainWith.loopandChainWith.last(RetWith.monofor the path out), andn.sound_loopis byKernel.sound_entryWithatcontract = true, whose per-thread premise also takes an admitted address choice and oracle and givesV.ctx.oracle = oracle k. Its instancekfK(MojoProofTest/KernelContract.lean) is the one-loop kernelkf(three rounds of%a = fadd contract (fmul contract %a, 2.0), 1.0) onL23, six threads. Its clause's preconditionpreFis the start's facts of some threadkwith a memory ofmemF k(some memorym₀with the caller's blocks,Elemfromm₀afterkthreads, andElem.Only), so it follows from the per-thread premise's facts for every admitted thread, and the tactic closes the four obligations at every valuation ofpreF, thread by thread (interval_casesonk, then evaluation in the kernel).kfK_retLsiskfK.loopat thread 0's valuationVF.kernelKiskfK.sound_loopwith every premise closed:IismemF,I 0bymemF_zero, the end bymemF_end(Elem.safe_on), onkfK.args 3 outF.2, every address choice and the oracleω₁, with the conclusionElem.OutofkernelF. The generated statement is unchanged:Idoes not depend on the start's memory, and the existential overm₀inmemFstands in for it. The open-goal test there checks the per-thread premise thatkernelKproves. With the flag and no loop clause, for a loop-free kernel,n.coversiscoversEntryWith trueandn.sound_ofisKernel.sound_of_chainsWithatcontract = true,n.coversand no sequence of loops (coversChainsWith true P fn [] = truebyrfl), so each thread's run is aRetWith truealong some path. Its instancekgK(MojoProofTest/KernelContract.lean) is the one-block kernelkg(fadd contract (fmul contract 3.0, 2.0), 1.0, stored). Withmap2, the flag givesn.retas aRetWith true, themojo_retproof of aRetmoved byRetWith.exists_true_of_ret, which covers only paths with nofmul contractproduct (decided bydecide +kernel; a kernel with one is refused at that check), andn.correctbyKernel.sound_map2With (contract := true); its instance ismap2_contract, on vadd's kernel incontractProg(vadd's program under another hash). Kernel.sound_cells(11) holds for every program, kernel, launch, admission, list of paths, list of sequences of loops, output block, cells and setSof threads that meet its premises;Kernel.sound_entry(12) for every program, kernel, launch, arguments, memory, admission, observation and predicate. In both, the per-threadRetorRetLsis the caller's premise. The instance ofKernel.sound_cells(MojoProofTest/KernelCells.lean) is one program and one launch:kc, a hand-builtFunc(as SymLoop'scnt) whose threads count%ifrom 0 to%nand then store it to cell%ctaid.x * %n + %tid.xif%tid.x < %n, onL23(two blocks of three threads) with%n = 2, the memoryoutM(one global block of fouri32cells), address choicech₀and oracleω₀. There the cells are apart on the storing threads (apartC, the instance ofapart_blocks, which holds at every block size, row length and width, also tested at blocks of 8 with rows of 5,apart_8_5) but not on all (not_apartC: thread 2, which skips, has thread 3's cell), soKernel.sound_elemdoes not apply. Each thread's run is checked by evaluation in the kernel on a memory symbolic but for its output block (kernel_check).Kernel.sound_cellsandKernel.sound_entrytakecoversChainsandRetLs, whose loops are checked withoutcontractflags on float operations;Kernel.sound_of_chainsWith(3),Kernel.sound_cellsWith(11) andKernel.sound_entryWith(12) hold for both flags, with the same generality.kernelF(MojoProofTest/KernelContract.lean) is an instance ofKernel.sound_mapNWith(11) atcontract = true, so ofKernel.sound_cellsWith, with every premise closed. It is one program and one launch:kf, a hand-builtFuncwhose threads run%nrounds of%a = fadd contract (fmul contract %a, 2.0), 1.0and store%ato cell%ctaid.x * %n + %tid.x, onL23with%n = 3, the memoryoutF(one global block of sixfloatcells), address choicech₀and the oracleω₁(everyfadd contractfuses). It has nobyvalstruct and two scalars (scF). Each thread's run is proved for every context and frame with the start's facts and every memory ofElemandElem.Only, by evaluation in the kernel one round at a time (roundsF,chainF_of). Its twin shows that the same proof atcontract = falsefails, since the checker withoutfmul contractrefuses the loop (chainF_refused). The one instance ofKernel.sound_mapNWithwith both abyvalstruct and a loop is the naive matmul kernel's (NaiveKernel.correct, throughKernel.sound_mat(13)), whose run of a thread in bounds is proved by hand (NaiveIn.runIn; the run out of bounds, loop-free, is generated,naive.out): a load from a struct's copy whose contents are a hypothesis (not a literal memory) is not discharged by evaluation in the kernel, andmojo_ret, which proves such loads, proves only loop-free paths. The other instances withbyvalstructs arevector_addition,vector_multiplyandvector_subtraction, without loops, throughKernel.sound_map2andKernel.sound_mapN, so throughKernel.sound_mapNWith.Kernel.sound_eval(5) holds for every program and kernel, at one launch, memory, address choice and oracle, where it reduces the theorem to Booleans the kernel decides. Its instancekernel22isvector_additionon 2 blocks of 2 threads with 3 elements, so threads 0 to 2 take the in-range path and thread 3 the other, on the pathsmojo_kernelgenerates (MojoProof/Kernels/Vadd.lean).Kernel.sound_elem(6) holds for every elementwise kernel that meets its premises,Kernel.sound_mapNWith(11) for the family of kernels whose parameters are any number ofbyvalbuffer structs then any number of scalars, with or withoutfmul contract, with loops, cells apart on a set of threads and every admitted oracle,Kernel.sound_mapN(6) for its case of one count of any type without loops at one oracle, andKernel.sound_map2(6) for the case of three structs and ani32count. In all of them the per-thread run is the caller's premise. The instances:kernelFofKernel.sound_mapNWith(no struct, two scalars, a loop withfmul contract), andKernel.sound_map2forvector_addition,vector_multiplyandvector_subtraction, whose per-threadRetthemap2clause ofmojo_kernelgenerates (the only clause that generates one for this family).Kernel.sound_mapNis proved fromKernel.sound_mapNWith, not fromKernel.sound_elem, whose statement is unchanged.Kernel.sound_map2With(6) holds for the same family with or withoutfmul contract(Kernel.sound_map2is it atfalse); its instance with the flag ismap2_contract(MojoProofTest/KernelContract.lean),vector_addition's kernel withcontractincontractProg(vadd's program under another hash, so that its theorems are not vadd's), whose paths record nofmul contractproduct.RetWith.exists_true_of_retholds for every valuation, predicate and list of paths none of whose summaries records one; a kernel whose paths record one is not covered by it (itsmap2clause withcontractfails atn.ret's check).Kernel.sound_mat(13) holds for the family of kernels whose parameters are threebyvalstructs then threei32scalars, with or withoutfmul contract, at every launch valid with side 1 inz, every memory with its premises and every admission; the per-thread runs and the start are the caller's premises. Thematclause ofmojo_kerneldischarges every premise but the memory's, the launch's and the run of a thread in bounds for one named kernel (n.sound_mat; the run out of bounds byn.out, whichRetWith.of_firstproves for every path the checker accepts that stores nothing after its entry block and returns). Its instance isNaiveSound.naive_sound, throughnaive.sound_mat, the one programnaivewithRunInas its premise, whichNaiveKernel.correctcloses withNaiveIn.runIn.Launch.apart_xy(11) holds for every valid launch with side 1 inz, stride, bounds and width. Its instanceapart2x3(MojoProofTest/KernelXY.lean) is one launch of 2 × 3 threads. Its twinnot_apart_xyholds for every valid launch with at least 2 rows ands + 1columns of threads, stridesbelow the column bound and width above 0: the premisen ≤ sis needed (the threads at row 0, columnsand at row 1, column 0 share cells * w); its tests areapart2x3_twin(stride 2, column bound 3) andapart4x5_twin(stride 4, column bound 5, two blocks).Elem.Out.of_run(10) holds for every run from a start; its instanceout_runis one run ofvector_addition(the memorymem5, count 5, the launch.one, address choicech₀and oracleω₀).vadd.correct(7) is about the one kernelvector_addition, at every valid launch whose grid and block have side 1 inyandzand every caller's memory ofMap2.Pre. It takes the per-threadRetfrommojo_ret(vadd.ret) and the start facts fromKernel.sound_map2(6) and 8. Its instances in MojoProofTest/Kernel.lean arecorrect23(2 blocks of 3 threads, 5 elements, nonconstant inputs onMap2.mem, every premise discharged) andcorrect12(one block of 2 threads, fewer than the 5 elements).vmul.correctis the same for the one kernel vector_multiply.- Not covered: calls to defined functions, barriers and shuffles.
The corollaries (9) are for every program and kernel whose theorem is Kernel.Sound for Elem.Out
with Elem.map2's bytes; their instances vadd_* and vmul_* cover what Kernels.vadd.correct
and Kernels.vmul.correct cover (every valid launch whose grid and block have side 1 in y and
z, memory of Map2.Pre, address choice and oracle). The checks by evaluation and the refutations
(10) are for one launch, memory, address choice ch₀ and oracle ω₀ each
(MojoProofTest/Kernel.lean): the satisfiability witness g2_vadd (Grid.start then Grid.run on
L23 with count 5 and mem5, whose final grid is done and meets Elem.outBelow and the sums cell
by cell; correct23 gives Elem.Out itself for it); the negative twins twin_len (a),
twin_alias (b), twin_tid (c) and twin_2d (d), each a ¬ Kernel.Sound for every observation,
relation and admission that admits ch₀ and ω₀ (Kernel.replay_unsafe), with the run that shows
what fails (run_len, a fault; run_alias, kept false without a race; run_tid, a race with its
two accesses; for (d) four launches, each with one of the four hypotheses on the launch false, a
race on each); and the canaries canaries_vadd,
canaries_vmul (Kernel.replay_canaries), whose controls are correct23 and correctV23.
Kernel.Sound's predicate R does not see the oracle. A result that names the oracle's numbers
(for vector_addition: cell i is fadd's value at thread i's oracle number) is stated for
every oracle ω with the admission fun _ o => o = ω and a predicate R ω.
Plan: the naive matmul's kernel theorem
Proved: the composition, from the threads' runs (MojoProofTest/NaiveSound.lean). The theorem
naive_sound is Kernel.Sound naive.prog naive.fn_0 L args mem (fun _ ω' => ω' = ω)
(fun m => some m.blocks) (Elem.Out mem bC (cell L) (bytes ω L K A B) N) (N the thread count;
S, cell, bytes, At, RunIn, RunOut of MojoProofTest/NaiveSpec.lean), for one program
(naive) at every oracle ω, every valid launch L with side 1 in z, every m, n ≤ 50257
and K ≤ 768 with the i32 products in range, every blocks bC, bA, bB, tensors A,
B and memory mem. It is Kernel.sound_mat (13) at contract := true, the paths [skipN],
the chains [chainN], the struct type NaiveSpec.T and tail NaiveSpec.z, alignment 8,
binary32 at alignment 4 and the strides 768, 768 and 50257, with the start by Grid.start_ok
(naive.starts) and the register names by naive.names; Kernel.sound_mat is
Kernel.sound_mapNWith at the blocks [bC, bA, bB] and the scalars %3, %4, %5, with the
cells by Launch.apart_xy. Its body applies naive.sound_mat, the call the mat clause of
mojo_kernel generates (the next section), with RunIn giving its one obligation and
naive.out the run of a thread out of bounds. Its premises, in the field order of Mat.Pre,
and what gives each:
mem.Closed args,bA ≠ bC ∧ bB ≠ bC, the threeMem.Buffers,Mem.HoldsofAandB, the bounds ofAt.dims, the threeMem.Fits: the caller's precondition, the projections ofMat.Pre(Sem/Precond.lean) at naive's layout,binary32, alignment 4 and the strides 768, 768 and 50257.Mat.pre_memprovesMat.Prefor all sizes atMat.mem, a memory of the three blocks built byMem.alloc.RunIn ω L K bC bA bB A B: a thread in bounds runschainNtoret, for every launch, thread and memory;NaiveIn.runInproves it for every oracle family, launch, sizes, blocks and tensors (docs/proofs/naive.md).- the sizes below
2 ^ 31(NaiveSpec.dims_lt, from the bounds ofAt.dims) and no bytes at a thread out of bounds (NaiveSpec.bytes_out):naive.out's premises. RunOut ω L K bC bA bB A B, a thread out of bounds runsskipNtoret, is no longer a premise:naive.outis that run atMat.Entry, andNaiveOut.runOutis its corollary atAtfor every oracle family, launch, sizes, blocks and tensors.
Kernel.sound_mat gives each thread its entry facts as one Mat.Entry (inside
Kernel.sound_mat, Mem.Buffer.of_block, Mem.Fits.of_block, Mem.Holds.of_block for A's
and B's blocks, Elem.buffer and Elem.fits for C's, and the case S L m n k or not picks
the premise); NaiveSpec.At.of_entry adds the launch's, the dimensions, the thread and ne,
with Mat.Entry's fields equal to At's by definition (idx "j" reduces to j). The
read-off is proved on the observation (Kernel.Obs) of every program whose kernel theorem has
this Elem.Out: naive_read gives, for r < m, c < n in the launch's window, the one
thread k of row r and column c (Launch.cell_onto, unique by Launch.xy_inj) whose 4
bytes at (r * 50257 + c) * 4 encode dotLoop true (o (ω k)) +0 (pairs A B r c K)
(Elem.put_read), the caller's bytes outside the cells of the threads in bounds
(Elem.put_out) and the caller's other blocks. naive_matmul,
for every K ≤ 768, compares each cell with entry (r, c) of TorchLean's Tensor.matmul of
the first K columns of A and of B, transposed (cols, Sem/Matmul.lean): NaNEq at a
thread whose oracle fuses no round (matmul_cols_nanEq), and within dotBound of the real
product when finite, for every oracle (matmul_cols_error).
Proved: the read-off at every stride (MojoProofTest/NaiveFam.lean). The naive family is the
program at row strides sA, sB (of A and B) and sC (of C); the corpus file is the one
at 768, 768 and 50257. NaiveFam.cell sC, NaiveFam.pairs (the first K of the min sA sB
pairs of row r of A, m × sA, and row c of B, n × sB) and NaiveFam.bytes are the
spec at every stride. NaiveFam.read is the read-off above for every program, function and
strides with n ≤ sC, from Kernel.Sound for Elem.Out of NaiveFam.bytes at cell sC
(Launch.apart_xy at row stride sC), and NaiveFam.matmul the comparison with TorchLean's
product for K ≤ sA and K ≤ sB (matmul_cols_nanEq, matmul_cols_error, which take the
first K columns of each). NaiveFam.cover is read when the window covers m × n,
NaiveFam.matmul_nanEq and NaiveFam.matmul_error are matmul's two clauses, and
NaiveFam.nanEq_zero is matmul_nanEq at the oracle family fun _ _ => 0, which fuses nothing.
naive_read and naive_matmul are read and matmul at 768, 768 and 50257, and
NaiveKernel.read_cover, matmul_nanEq, matmul_error and nanEq_zero the other four there
at correct, one line each; read_16_8_5, matmul_16_8_5, cover_16_8_5,
matmul_nanEq_16_8_5, matmul_error_16_8_5 and nanEq_zero_16_8_5 are the six at strides 16,
8 and 5.
The kernel's soundness at a stride other than the corpus's is not proved: the program at every
stride is not built, and the run of a thread in bounds (runIn) is proved through summaries
computed on the corpus program.
Proved: the kernel theorem (MojoProofTest/NaiveKernel.lean). NaiveKernel.correct hL hz h
is naive_sound with runIn: naive is sound for Elem.Out of its bytes at every
oracle family, valid launch with side 1 in z, sizes, blocks, tensors and memory h : Mat.Pre
at naive's constants, with no premise on the threads. naive_read and naive_matmul read its
cells. sound12 is its instance at one block of 2 × 2 threads with m = 1, n = 2 and
K = 768 (threads 0 and 2 in bounds, 1 and 3 not, in12) on mem12, Mat.mem with C, A
and B at blocks 1, 2 and 3 (pre12, by Mat.pre_mem), for every A, B and oracle family.
It covers the one program naive, at every launch and memory of its family; it is
naive_sound at the run in bounds, so the call of Kernel.sound_mat and the run out of bounds
in it are the ones mojo_kernel generates, and the run in bounds is by hand. Its corollaries, each
NaiveFam.cover, matmul_nanEq, matmul_error or nanEq_zero at the corpus strides and
correct with the observed block from Mat.Pre, one line each, cover the same family:
read_cover: when the window coversm × n(m ≤ grid.x * block.x,n ≤ grid.y * block.y), every cell(r, c)withr < m,c < nholds the contracted dot loop of its one thread; the window premises ofnaive_readare gone (NaiveFam.cover). Its instanceread12readssound12's two cells; its twinkeep11, on the one-thread launchLaunch.oneat the same memory (window 1 × 1,n = 2), shows bynaive_read's second clause, with no evaluation, that every byte ofCfrom offset 4 on, soC[0, 1], is the caller's.matmul_nanEq: each cell in bounds and in the window isNaNEqto entry(r, c)of TorchLean'sTensor.matmulof the firstK ≤ 768columns, at a thread whose oracle fuses no round (nofaddoracle number2modulo3). The equality needs that premise: a fused round rounds the product and the sum once, TorchLean's product rounds each.nanEq_zerois it at the oracle familyfun _ _ => 0, which fuses nothing, with the premise discharged.matmul_error: each finite cell in bounds and in the window is withindotBoundof binary32 atKof the real product, at every oracle family.
What remains.
- The naive kernel's roadmap card: its L3 and L4 evidence from
NaiveKernel.matmul_nanEqandNaiveKernel.matmul_error, and a GPU run for L1. - The run of a thread in bounds is not generated. The
matclause (the next section) generates the call ofKernel.sound_mat(13) and the run of a thread out of bounds (naive.out), sonaive_soundis one term.RunIn(MojoProofTest/NaiveSpec.lean) takes the facts as oneNaiveSpec.At, with the registers namedidx "j", so the term turnsMat.EntryintoAt(NaiveSpec.At.of_entry). The run in bounds isNaiveIn.runIn, by hand; the end of the next section has a design, not implemented, for generating it from an invariant. - The
loopclause on the naive loop: with the flagcontractits obligations,n.loopandn.sound_loopare theWith trueforms, but the naive loop's obligations (an invariant overdotLoop's accumulator, for every launch and every trip countsmax(K, 0)) are not proved, andn.sound_loopgives no register fact for the threebyvalstructs (the next section's clause takes the chains as arguments instead).
The rest of this section is the earlier plan of the whole proof. The kernel is the one function
matmul_kernel_naive_float32_float32_float32_True_16_16826c8c
(tests/corpus/mgemm/g_matmul_kernel_naive_float32_float32_float32_True_16_16826c8c.nvptx.ll). Its
parameters are three byval buffer structs %0 (C), %1 (A), %2 (B) and the i32 scalars
%3 = m, %4 = n, %5 = K. Thread k has row r = L.index k .x (%24, ctaid.x * ntid.x +
tid.x) and column c = L.index k .y (%35). If r ≥ m or c ≥ n (signed, %43) it returns
(%44, %69). Otherwise it runs the loop at header %46 from %47 = 0 and the accumulator
%48 = 0.0 (the float constant of the edge from %45) while %47 < smax(K, 0) (%16); the
body %52 loads A[r * 768 + i] and B[c * 768 + i] (i32 arithmetic, then sext;
!invariant.load) and computes %66 = fadd contract %48 (fmul contract a b); the exit %67
stores the accumulator at C[r * 50257 + c] (i32 arithmetic, then sext).
Statement. For every valid launch L with side 1 in z (L.grid .z = 1 ∧ L.block .z = 1),
every m, n ≤ 50257 and K ≤ 768 with the i32 products in range (m * 50257 < 2 ^ 31,
m * 768 < 2 ^ 31, n * 768 < 2 ^ 31), every oracle ω, and every caller's memory whose
pointer bytes are known, with distinct blocks for C (room for m * 50257 cells), A (holding a
row-major m × 768 tensor of binary32 words, Block.Holds at rowMajor) and B (an n × 768
tensor): the kernel on these arguments is Kernel.Sound at the admission fun _ o => o = ω
for the observation of the blocks and the predicate that every block but C's is the caller's,
and cell (r, c) of C, for r < min m X and c < min n Y (X = L.grid .x * L.block .x,
Y = L.grid .y * L.block .y, the launch's rows and columns), holds the word
dotLoop true (o ω r c) +0 (matmulPairs A_K (B_K)ᵀ r c), where A_K and B_K are the first
K columns, (B_K)ᵀ is TorchLean's Tensor.permute of B_K, and o ω r c j is the pair of
the oracle numbers of thread (r, c) at positions 54 + 18 j and 55 + 18 j (the fmul and
fadd of round j). Every other cell of C is the caller's. Since Kernel.Sound's predicate
does not see the oracle (see the end of Scope), the statement is one for each ω. Its
corollaries against TorchLean are Sem/Matmul.lean's: at an oracle that never fuses (no fadd number
2 modulo 3), matmul_cell_nanEq and matmul_cell_eq give cell (r, c) equal to
get2 (Tensor.matmul A_K (B_K)ᵀ) r c up to NaNs; at every oracle, matmul_cell_error bounds a
finite cell's distance from the real matmul.
Premises and the module whose theorem gives each. Every name in this list is in the tree.
Of the proof after the list, steps 1, 2 and 5 and the cell fact are in Lean
(Kernel.sound_of_chainsWith, Kernel.sound_cellsWith, Kernel.sound_mapNWith,
Launch.apart_xy, and naive_sound and naive_read of MojoProofTest/NaiveSound.lean); steps 3
and 4 are the statements RunOut and RunIn of MojoProofTest/NaiveSpec.lean.
- The semantics (Sem/Index.lean, Sem/Dot.lean, Sem/Matmul.lean): the 2-D cells,
Launch.apart_xyats = 50257,n ≤ 50257andw = 4(fromLaunch.cell_apartat base 0), which givesApart (fun i : {i // S i} => cell i) 4forS k := k < N ∧ L.index k .x < m ∧ L.index k .y < nandcell k := (L.index k .x * 50257 + L.index k .y) * 4;Launch.index_opsfor the index words%24and%35;rowMajor_twoandMem.load_get2for the words the loads return;get2_swapandmatmulPairs_swapforBᵀ;dotLoop_of_floatBinandcell_of_floatBinfor the accumulator afterKrounds againstdotLoop true;matmul_cell_nanEq,matmul_cell_eq,matmul_cell_errorfor the corollaries. - The loop checker (Sym/Loop.lean, MojoProofTest/SymNaive.lean): the naive loop's
LoopSegnaiveLwith its rounds checked with thefmul contractflag (RoundWith true,coversChainsWith true), the header'sphi floatof%45's constant0.0, andRuns.of_chainsWithfor the thread's run; theLoopChainfrom the entry through%45tonaiveL, its path out%46 → %51 → %67 → %69, and the skip path%6 → %44 → %69. - The obligation prover (Sym/Obl.lean, Sym/Ops.lean):
mojo_oblfor the round obligations over the runtime trip countsmax(K, 0)(a bound that is not a literal), andmojo_ret-style obligations for the index and address arithmetic of the entry block and the store. - The kernel theorem (this file):
Kernel.sound_mapNWith(11) atcontract = true,bl = [C, A, B]andscthe threei32scalars, with the start facts.
Proof, through Kernel.sound_mapNWith.
- A
contractform of 3 and 11 (in Lean).Kernel.sound_of_chainsWithandKernel.sound_cellsWithtakecoversChainsWith contractandRetLsWith contract, which the naive loop needs attrue;Kernel.sound_of_chainsandKernel.sound_cellsare theirfalsecases, one line each. - The start facts for three
byvalstructs and three scalars (in Lean).Kernel.sound_mapNWith's per-thread premise gives each struct's register pointing to a block other than C's from which the struct loads (Grid.start_buffer), the registers%3to%5holdingm,n,K(Grid.start_scalar), the context (Grid.start_ctx) and the caller's blocks unchanged (Grid.start_blocks,Elem.start_block). - A thread outside
Stakes the skip path, the first disjunct: aRetwith no effect to C,Elem.skipatbs k = none, andElem.Onlykept since its only accesses are the loads of its struct copies (Elem.Only.apply). - A thread of
Sruns theLoopChain, the second disjunct, at the invariant of roundj:%47 = j,%48the accumulatoracc jofdotLoop_of_floatBin, and the memory the entry's with the loads of rounds< jlogged (Elem.apply_load,Elem.Only.apply: the loads are to A's and B's blocks, not C's); trip countK(smax(K, 0) = Kfor0 ≤ K) bymojo_obl. The path out storesacc Kat the thread's cell (Elem.apply_store,Elem.Only.apply) withbs kits encoding, andcell_of_floatBinnames itdotLoop true (o ω r c) +0 (matmulPairs …). - The end:
Kernel.sound_mapNWithgivesElem.Outfor the blocks.Elem.put_read, whose cells are apart only on the threads with bytes (those ofS; two threads outsideSmay share a cell), reads cell(r, c)asbs kfor the one threadkwithL.index k .x = randL.index k .y = c(Sem/Index.lean'sLaunch.xy_injandcoord_linear), and every other cell as the caller's.
What it does not cover: launches with side other than 1 in z (two threads then share a cell, as
the twin of Launch.cell_apart without side 1 in z shows), K > 768 or n > 50257 (the
strides are the corpus's constants), and the i32 products out of range.
The 2-D clause of mojo_kernel (mat)
The clause mat makes mojo_kernel state and prove the kernel theorem of a matmul kernel, with
the run of a thread in bounds as the one premise the user proves. It is the call of
Kernel.sound_mat (Sym/KernelMat.lean) with every premise that depends only on the program
discharged, the run of a thread out of bounds among them. It is implemented by elabMat
(Sym/KernelCmd.lean, step 7 of the command), and its instance is the naive matmul kernel.
Syntax. mat paths chains is the last clause group, after contract:
mojo_kernel naive := naive.prog naive.fn_0 reads bA := a1, bB := a2 writes bC := a0
scalars m := a3, n := a4, K := a5 contract mat [skipN] [chainN]
paths : List (List (Nat × List Cond × Summary))is the kernel's loop-free paths from the entry block, andchains : List LoopChainis its sequences of loops. Both are terms, asKernel.sound_mattakes them.- The clauses must be
readsofa1anda2,writesofa0, andscalarsofa3,a4anda5(the command's clause order isreads,writes,scalars). Their names are the binder names of the inputs, the output and the sizesm,n,K. contractis optional withmat. It setsKernel.sound_mat's flag, so the path checker and the runs are the variants withfmul contract. Withoutmat,contractgoes with a loop clause, withmap2, or with neither for a loop-free kernel.matis not combined withmap2orloop.
The chains are arguments, not computed. The loop clause computes the chains from the
header, but it needs its own obligations (pre, inv, trips and post over valuations), and
their shapes carry neither the memory facts of Kernel.sound_mat's per-thread premises (Elem,
Elem.Only, the buffers) nor the 2-D index facts. The runs are proved over the given chains
instead. For naive, NaiveIn.runIn proves the run over chainN through
NaiveThread.thread_run. The command checks the given paths and chains with the path checker,
by evaluation, before it adds anything. So a wrong chain is refused, and it cannot make a
theorem hold.
Checks, each an error naming the reason and fn; a refused command adds nothing:
fnelaborates to a constant;Phas no globals;fnhas six parameters. The first three arebyvalof one struct typeT, a pointer of address spacespthen a tailuwith a zero valuez(Layout.zero). The last three arei32withoutbyval.- parameter
jhas register namej; - the clauses are as above, and their names are not binder names of the generated theorems
(
matBinders, those ofn.sound_matandn.out); pathsandchainsare not empty, evaluated before the path checker;- the path checker accepts the arguments:
coversEntryWith contract P fn pathsandcoversChainsWith contract P fn chains, evaluated.
The messages begin mojo_kernel: mat and end with fn, for example mojo_kernel: mat needs a
kernel of six parameters, three byval structs then three i32s; edgeF has 0. The checker's cover
of an empty list is vacuous. With mat [] chains the theorem would still be true, since
Kernel.sound_mat is proved for every list, but its Hout would hold only at a launch with no
thread out of bounds (and n.out would not elaborate). An empty chains would likewise give a
Hin that holds only with no thread in bounds. So the clause refuses an empty list
(mojo_kernel: mat needs a path; with no paths the theorem covers only launches with no thread
out of bounds (naive.fn_0), and the same with a chain).
What it generates. It adds four theorems and no definition:
n.starts: the start onMat.args z o a b m n Ksucceeds for every launch, block numbers, sizes, memory closed for the arguments, address choice and oracle. It isSym.Grid.start_ok, proved as the other clauses'n.starts.n.names: parameterjoffnhas register namej, for eachj. It is proved bydecide +kernel.n.out: a thread out of bounds runs some path of the clause toret, from the entry factsMat.Entry, the sizes below2 ^ 31and no bytes at a thread out of bounds. Its proof is below (Houtdischarged).n.sound_mat: the kernel theorem. It isKernel.sound_matwith these premises discharged:- the paths and the chains, each by
decide +kernel; - the parameter list, by
rfl, and the names, byn.names; byvalofTfor the structs and none for the sizes, byrfl;- the codec of
T, byLayout.Codec.ptrArgatsp; - the alignment
al', which isP.layout.align Tevaluated, bydecide; withAttrsof the three words, byrfl;- the start, by
n.starts; Hout, byn.out.
- the paths and the chains, each by
No n.covers or n.coversChains is added, since a theorem with the chains' type can already
exist (for naive, chainN_covers). No n.args, n.argTy or n.argTail is added either: the
arguments are Mat.args at z, and T and z are written into the statement as literals.
The entry facts as a structure (Mat.Entry). Kernel.sound_mat's per-thread premises
stated a thread's entry facts as 25 separate binders: the context (3), the frame's function, the
struct pointers and their blocks (6), the loads (3), the scalars (3), the three buffers on m'
(8). The naive instance repacked them into NaiveSpec.At, whose fields state the registers as
idx "j": six facts idx "j" = j by decide +kernel and two 9-line lambdas, 19 proof lines.
They are now one premise Mat.Entry prog fn L T z al' t enc al o a b K sC x y k c q0 q1 q2 m' f
(Sym/KernelMat.lean), a structure with the fields ctx, func, ptrs, loads, scalars,
bufA, bufB, bufC, in that order and grouped as NaiveSpec.At groups them. idx "j"
reduces to j by rfl, so At's fields and Mat.Entry's are equal by definition and
NaiveSpec.At.of_entry and NaiveSpec.At.entry are anonymous constructors of the fields, no
rewriting. NaiveSpec.At keeps its fields, since NaiveIn.lean and NaiveStart.lean use them.
Hout discharged (RetWith.of_first, n.out). A thread out of bounds takes a path that
branches at the entry block to the exit and stores nothing. The library theorem, for every flag,
valuation, predicate and path the checker accepts:
theorem RetWith.of_first {contract : Bool} {V : Valuation} {Q : Mem → Prop} {l : Nat}
{ds : List Cond} {S : Summary} {ps : List (Nat × List Cond × Summary)}
(hp : Cond.mem S.effs ∈ ds ∧ (∀ b ∈ ps, b.2.2.effs = []) ∧
((l, ds, S) :: ps).getLast?.map (·.2.2.exit) = some .ret)
(hW : WalkWith contract V ((l, ds, S) :: ps))
(hQ : ∀ me, SEff.run V (vals V S.nodes) S.effs = .ok me → Q me) :
RetWith contract V Q ((l, ds, S) :: ps)
If the first block's conditions include its effects' run (Cond.mem, which the summarizer
adds for every block with effects), the later blocks have no effects and the last one returns,
then the walk and the predicate at the first block's memory give RetWith. The memory after
the walk is the first block's (Valuation.lastWith_noEffs) and the last exit is the path's last
summary's (Valuation.lastWith_exit). hp is a fact of the path's data, so decide +kernel
proves it at a concrete path.
n.out is generated, one term per kernel:
theorem naive.out {L : Launch} (hL : L.Valid) {bC bA bB m n K : Nat} {α : Type}
[TorchLean.Storage α] {t : Ty} {enc : α → Val} {al sA sB sC : Nat}
{x : TorchLean.Tensor α [m, sA]} {y : TorchLean.Tensor α [n, sB]} {w : Nat}
{bs : Nat → Option (List MemByte)} (hsz : m < 2 ^ 31 ∧ n < 2 ^ 31 ∧ K < 2 ^ 31)
(hbs : ∀ k, ¬ S k → bs k = none) {k q0 q1 q2 : Nat} {c : Ctx} {m₀ m' : Mem} {f : Frame}
(hk : k < volume L.grid * volume L.block) (hS : ¬ S k)
(h : Mat.Entry naive.prog naive.fn_0 L T z 8 t enc al bC bA bB K sC x y k c q0 q1 q2 m' f)
(hE : Elem m₀ bC w cell bs k m') (hO : Elem.Only bC S m') :
∃ ps ∈ [skipN], RetWith true (Valuation.entry c 0 m' f)
(fun me => Elem m₀ bC w cell bs (k + 1) me ∧ Elem.Only bC S me) ps
Its proof takes h's fields, splits on the thread's row (L.index k .x < m or not; in the
first case the column is at least n, from hS), restates the row and the column as the sums
of special registers mojo_obl reads, and tries each path of the clause in order with
RetWith.of_first (by decide +kernel) (by mojo_obl) fun me hme => ⟨Elem.skip (by mojo_ret) hb,
by mojo_ret⟩. The branch out of bounds is one of the walk's conditions, and mojo_obl
discharges it from the 2-D index facts and the sizes below 2 ^ 31 (the i32 compares). The
memory is the first block's loads, which put no bytes (Elem.skip, with hbs) and add no
access to bC (mojo_ret). If no path is discharged, the command fails with {n}.out does not
elaborate: no path of the clause is discharged for a thread out of bounds and adds nothing.
The obligation is closed in general for a kernel whose skip path is of that shape; a kernel
whose out-of-bounds path stores, or whose branch needs facts mojo_obl does not find by type,
is refused, not given a named obligation.
What moved, by statement. Kernel.sound_mat's Hin and Hout changed: the 25 entry-fact
binders are one Mat.Entry, and the binders are reordered k q0 q1 q2 c m₀ m' f (all before the
premises). n.sound_mat gained hsz and hbs (the premises of n.out) and lost Hout.
NaiveSound.naive_sound lost hout (a deliberate restatement: a thread out of bounds is no
longer a premise), and its proof is one term. NaiveOut.runOut keeps its statement; its proof is
naive.out at At's facts. NaiveKernel.correct keeps its statement and passes only
NaiveIn.runIn.
The generated statement, for naive, before. Here z stands for the tail's zero value
.agg [.agg [.agg [], .agg []], .agg [.agg [], .agg []]], and T for the struct type
.struct [.ptr 0, .struct [.struct [.struct [], .struct []], .struct [.struct [], .struct []]]]:
theorem naive.sound_mat {L : Launch} (hL : L.Valid) (hz : L.grid .z = 1 ∧ L.block .z = 1)
{bC bA bB m n K : Nat} {α : Type} [TorchLean.Storage α] {t : Ty} {enc : α → Val}
{al sA sB sC : Nat} {x : TorchLean.Tensor α [m, sA]} {y : TorchLean.Tensor α [n, sB]}
{mem : Mem} (hC : mem.Closed (Mat.args z bC bA bB m n K)) (hne : bA ≠ bC ∧ bB ≠ bC)
(hbuf : mem.Buffer bA (m * sA * naive.prog.layout.size t) al false ∧
mem.Buffer bB (n * sB * naive.prog.layout.size t) al false ∧
mem.Buffer bC (m * sC * naive.prog.layout.size t) al true)
(hx : mem.Holds naive.prog.layout bA t enc (rowMajor naive.prog.layout t 0) x)
(hy : mem.Holds naive.prog.layout bB t enc (rowMajor naive.prog.layout t 0) y)
(hsC : n ≤ sC)
(hfit : mem.Fits naive.prog.layout bA (m * sA * naive.prog.layout.size t) ∧
mem.Fits naive.prog.layout bB (n * sB * naive.prog.layout.size t) ∧
mem.Fits naive.prog.layout bC (m * sC * naive.prog.layout.size t))
{adm : (Nat → Nat) → (Nat → Nat → Nat) → Prop} {w : Nat}
{bs : Nat → Option (List MemByte)}
(Hin : ∀ ch oracle, adm ch oracle → ∀ k,
(k < volume L.grid * volume L.block ∧ L.index k .x < m ∧ L.index k .y < n) →
∀ c : Ctx, c.prog = naive.prog → c.env = L.env k → c.who = ⟨k, k / volume L.block⟩ →
c.oracle = oracle k → ∀ (m₀ m' : Mem) (f : Frame), f.fn = naive.fn_0 → ∀ q0 q1 q2,
-- the struct pointers in %0 to %2, their loads at alignment 8, the words of m, n, K in
-- %3 to %5, the buffers on m', Elem after k threads and Elem.Only, as in Kernel.sound_mat
… →
∃ C ∈ [chainN], RetLsWith true (fun me => Elem m₀ bC w cell bs (k + 1) me ∧
Elem.Only bC S me) C.loops (Valuation.entry c 0 m' f) C.l C.ds C.S C.E)
(Hout : ∀ ch oracle, adm ch oracle → ∀ k, k < volume L.grid * volume L.block → ¬ S k →
… (the same facts) →
∃ ps ∈ [skipN], RetWith true (Valuation.entry c 0 m' f)
(fun me => Elem m₀ bC w cell bs (k + 1) me ∧ Elem.Only bC S me) ps) :
Kernel.Sound naive.prog naive.fn_0 L (Mat.args z bC bA bB m n K) mem adm
(fun m => some m.blocks)
(Elem.Out mem bC (fun k => (L.index k .x * sC + L.index k .y) * w) bs
(volume L.grid * volume L.block))
After. The premises up to hfit are the same:
theorem naive.sound_mat … (hfit : …)
{adm : (Nat → Nat) → (Nat → Nat → Nat) → Prop} {w : Nat}
{bs : Nat → Option (List MemByte)} (hsz : m < 2 ^ 31 ∧ n < 2 ^ 31 ∧ K < 2 ^ 31)
(hbs : ∀ k, ¬ S k → bs k = none)
(Hin : ∀ ch oracle, adm ch oracle → ∀ k q0 q1 q2 (c : Ctx) (m₀ m' : Mem) (f : Frame), S k →
c.oracle = oracle k →
Mat.Entry naive.prog naive.fn_0 L T z 8 t enc al bC bA bB K sC x y k c q0 q1 q2 m' f →
Elem m₀ bC w cell bs k m' → Elem.Only bC S m' →
∃ C ∈ [chainN], RetLsWith true (fun me => Elem m₀ bC w cell bs (k + 1) me ∧
Elem.Only bC S me) C.loops (Valuation.entry c 0 m' f) C.l C.ds C.S C.E) :
Kernel.Sound naive.prog naive.fn_0 L (Mat.args z bC bA bB m n K) mem adm
(fun m => some m.blocks)
(Elem.Out mem bC (fun k => (L.index k .x * sC + L.index k .y) * w) bs
(volume L.grid * volume L.block))
In Hin and Hout, cell is fun k => (L.index k .x * sC + L.index k .y) * w, and S is the
threads in bounds, fun k => k < volume L.grid * volume L.block ∧ L.index k .x < m ∧
L.index k .y < n. Both are written out in the statement. The statement covers this one kernel
at every launch valid with side 1 in z, every element type, encoder, alignment, strides,
tensors and memory with the memory premises, every admission, cell width and bytes.
What is left to the user. The user proves the run of a thread in bounds, Hin (it runs a
chain to ret), from Mat.Entry. The memory premises are the caller's, and Mat.Pre
(Sem/Precond.lean) gives all of them; hsz follows from the i32 products of Mat.Pre at a
concrete stride (NaiveSpec.dims_lt) and hbs from the bytes' definition
(NaiveSpec.bytes_out).
The instance. MojoProofTest/NaiveSound.lean runs the command above.
naive_soundloses its premisehout. Its proof is the termnaive.sound_matat binary32, alignment 4 and strides 768, 768, 50257,dims_lt,bytes_out, andHinfromhin(NaiveSpec.RunIn) throughNaiveSpec.At.of_entry.NaiveKernel.correctkeeps its proof,naive_soundatNaiveIn.runIn.NaiveOut.runOutkeeps its statement (NaiveStart.lean uses it). It isnaive.outatNaiveSpec.At.entry.- The hand theorems
startsandnamesof MojoProofTest/NaiveSound.lean are deleted. The generatednaive.nameshas the statement of the handnames; the generatednaive.startshas the handstarts's, with the tail written as a literal where the hand one hasNaiveSpec.z. naive.sound_mathas its premise inMat.Entryform wherenaive_soundhasRunIn, andnaive.out's conclusion isRunOut's body atMat.Entry, so no two theorems have one statement (DUPTHM, by the elaborated type).
Tests (MojoProofTest/NaiveSound.lean, section Clause).
- An open-goal test (
#guard_msgs) shows the one obligation,case Hin, as the goalnaive.sound_matleaves at every launch and memory ofMat.Preat naive's constants. - Five refusals, each with its message:
maton a kernel whose parameters are not threebyvalstructs and threei32s (edgeF, of no parameters);- on
naivewith the reads in the other order (bA := a2, bB := a1); - on
naivewith a clause namedx, a binder name of the generated theorems; - on
naivewith no paths (mat [] [chainN]) and with no chains (mat [skipN] []).
- Three refusals of the path checker (
naiveA,naiveB,naiveV): onnaivewith a path, and with a chain without and withinv, whose first block is not the entry block. The checks before the path checker (the empty lists,inv's chain) evaluate terms too; the command then sets the macro-scope counter back, so the generated binder names do not depend on them, and the path checker's own evaluations may reuse the checks' names for their temporary declarations. These refusals show that its values are its own. - A refusal of
n.out(naiveO): onnaivewith one path,chainN's path in, then the loop head and the path out with no round. The checker accepts it, but the path out stores the cell (%67) and the entry block's branch on it is the one of a thread in bounds, so no path of the clause is discharged for a thread out of bounds. The command adds nothing, and the attempt's own errors are dropped: the one message isn.out's.
What the clause does not do.
- It does not find the invariant of a thread in bounds.
mojo_retproves onlyRetalong loop-free paths, and the loop clause's tactic evaluates each thread of one concrete launch; it does not prove the invariant overdotLoop's accumulator at every launch. Withinv(below) the clause proves the run from an invariant and its three obligations, which the user proves. - It does not give a named obligation when no path is discharged for a thread out of bounds; it refuses the command.
Hin from an invariant (mat paths chains inv)
With the keyword inv after the mat clause's two terms, the clause also proves Hin from an
invariant, so that the user proves a loop invariant and its three obligations instead of the
whole run of a thread in bounds.
What the run was made of. MojoProofTest/NaiveIn.lean proves Hin (as runIn). Before the
clause, its proof was NaiveThread.thread_run at the predicate Head and four theorems:
entry_in(deleted since; the clause discharges it): the entry block's obligations and its branch to the loop head (OblMatmul.naive_entry, bymojo_obl), fromAt's facts (Mat.Entry's and the launch's);head_in: the invariantNaiveThread.Invat round 0 andHeadat the loop head (obl_have);round_in: one round's premises (RoundWith, fromOblMatmul.naive_rounds),Headafter it, the counterj + 1and the accumulator'sfaddof the round's pair;exit_in: the path out returns withElemafterk + 1threads andElem.Only(OblMatmul.naive_exit,Elem.apply_store,Elem.Only.apply).
thread_run's loop part is not about naive's arithmetic: Round.of_inv, then
ChainWith.of_rounds, then the path out as .last, with the step counts from
Valuation.roundWith_k.
The library theorem RetLsWith.of_inv (Sym/KernelMat.lean, with Kernel.sound_mat, whose
premise it proves; Sym/Loop.lean keeps the checker's interface):
theorem RetLsWith.of_inv {contract : Bool} {Q : Mem → Prop} {L : LoopSeg} (hL : L.inner = [])
{V : Valuation} {l : Nat} {ds : List Cond} {S : Summary}
{E : List (Nat × List Cond × Summary)} (n : Nat) (I : Nat → Valuation → Prop)
(hE : EdgeWith contract L.h L.p V l ds S E)
(h0 : I 0 (Valuation.roundWith contract l S E V))
(hR : ∀ i < n, ∀ W, W.ctx = V.ctx →
W.k = (Valuation.roundWith contract l S E V).k + i * (pathLen L.H L.B + 1) → I i W →
RoundWith contract L.h L.p L.dh L.H L.B W ∧
I (i + 1) (Valuation.roundWith contract L.h L.H L.B W))
(hX : ∀ W, W.ctx = V.ctx →
W.k = (Valuation.roundWith contract l S E V).k + n * (pathLen L.H L.B + 1) → I n W →
RetWith contract W Q ((L.h, L.dh, L.H) :: L.X)) :
RetLsWith contract Q [L] V l ds S E
V₀ = Valuation.roundWith contract l S E V is the header's entry valuation after the path in.
The context and step-count premises let a round's float operations name their oracle numbers.
The proof is Round.of_inv at I strengthened with the context and the step count (each round
keeps the context and adds pathLen L.H L.B + 1 steps, Valuation.roundWith_k), then
ChainWith.of_rounds with the path out as ChainWith.last. It covers one loop with no nested
loop; a sequence of several loops, or a nested loop, is ChainWith.loop with one invariant per
loop.
Its instances at naive (MojoProofTest/NaiveThread.lean; the statements are unchanged):
thread_runisRetLsWith.of_invatchainNwithI j W := Inv (oN V.ctx V.k) ps j W ∧ G W, the edge from the entry block's premise andSymNaive.pre_edge, and each round from the newround_inv: from the round's premises,Gand the two registers after the round (the conclusion ofNaiveIn.round_in), it gives the round's premises andI (j + 1), the accumulator's step byfloatBin_dotStep, as before;thread_skipisRetWith.of_firstatskipN:%44and%69have no effects.
Hand-written proof lines of NaiveThread.lean (the lines of the proofs, after the top-level :=,
not blank or comment): 178 before, 141 after; thread_run 47 to 12, thread_skip 41 to 9, and
round_inv 30.
Syntax. mat paths chains inv, a keyword with no terms:
mojo_kernel naive := naive.prog naive.fn_0 reads bA := a1, bB := a2 writes bC := a0
scalars m := a3, n := a4, K := a5 contract mat [skipN] [chainN] inv
The invariant I is a binder of the generated theorems, not a term of the clause; the trip count is
max K 0 (smax(K, 0), K the clause's third size), which the command states. n.sound_mat is
stated for every element type, encoder, row strides, tensors, cell width and bytes, so a clause term
about the instance's tensors (for naive, pairs A B r c K at binary32 and stride 768) does not type
there. It would also name variables that exist only where the theorem is used (A, B, the oracles
ω). As a binder, I is chosen by the caller, as bs is, and takes a thread's facts as its
argument:
{I : Mat.Thread prog fn L T z al' t enc al o a b K sC x y adm w bs → Nat → Valuation → Prop}
Mat.Thread (Sym/KernelMat.lean) is a structure of what Hin gives a thread in bounds: the
choice and the oracles with admits, the index k, the struct values q0, q1, q2, the
context c, the memories m₀ and m', the frame f, and the facts inBounds (S k, the
threads in bounds written out: k < volume L.grid * volume L.block ∧ L.index k .x < m ∧
L.index k .y < n), oracleEq (c.oracle = oracle k), entry (Mat.Entry), elem and
only (Elem after k threads and Elem.Only at m'). For naive, max K 0 is also the
length of pairs A B r c K (K ≤ 768; the row r and column c are Fins from
th.inBounds).
Checks, in addition to mat's, before the path checker; each an error naming fn:
chainsreduces (whnf) to a list of one chainC;C.loopsreduces to a list of one loopLp;Lp.innerreduces to[].
The messages are mojo_kernel: mat: inv needs one chain …, … a chain of one loop … and
… a loop with no nested loop ….
What it generates. The four theorems of mat, with the same statements, and two more:
n.runInv: the run of one thread in bounds, for every launch valid, block numbers, sizes below2 ^ 31, element type, encoder, alignment, strides, tensors, cell width, bytes, threadkin bounds (hS) with the factsMat.Entry(h), the inputs other than the output (hne), a memory ofElemandElem.Only(hE,hO), invariantIandH : LoopIterWith … (max K 0) (Mat.Head …) Iat the thread's entry valuation. Its proof isRetLsWith.of_iter rflwith the edge into the loop bymojo_oblat the thread's 2-D index facts (asn.out's premises are),Mat.Headat every head of a round (below) andH. If one of the two is not discharged, the command is refused (mojo_kernel: mat: inv: n.runInv does not elaborate: the edge into the loop is not discharged by mojo_obl …, orMat.Headat the loop head is not proved by mojo_inv and obl_have …) and adds nothing.n.sound_inv:n.sound_mat's statement withHinreplaced by one premiseH,LoopIterWithwithMat.Headat each threadth : Mat.Thread …atI thandmax K 0(Iimplicit). Its proof isKernel.sound_matat the same arguments asn.sound_mat's, withHinbyn.runInvat the thread's facts andHat theMat.Threadof them.
Old and new premise. n.sound_mat's Hin (unchanged, above):
(Hin : ∀ ch oracle, adm ch oracle → ∀ k q0 q1 q2 (c : Ctx) (m₀ m' : Mem) (f : Frame), S k →
c.oracle = oracle k → Mat.Entry … → Elem m₀ bC w cell bs k m' → Elem.Only bC S m' →
∃ C ∈ [chainN], RetLsWith true (fun me => Elem m₀ bC w cell bs (k + 1) me ∧
Elem.Only bC S me) C.loops (Valuation.entry c 0 m' f) C.l C.ds C.S C.E)
n.sound_inv's one premise at naive, with Q th the post-condition of Hin at the thread
(Elem th.m₀ bC w cell bs (th.k + 1) me ∧ Elem.Only bC S me) and V th its entry valuation
Valuation.entry th.c 0 th.m' th.f:
(H : ∀ th : Mat.Thread …, LoopIterWith true naiveL (V th) chainN.l chainN.S chainN.E (Q th)
(max K 0) (Mat.Head naive.prog naive.fn_0 … th.k th.m₀ S) (I th))
LoopIterWith (Sym/KernelIter.lean) is the three premises after the edge at the heads of the
rounds, below. Until the change described there, the premise was LoopInvWith
(Sym/KernelMat.lean), the three premises of RetLsWith.of_inv at every valuation of the
invariant, with no facts F.
Before, each of the three premises Hhead, Hround and Hexit repeated Hin's binders (∀ ch
oracle, adm ch oracle → ∀ k q0 q1 q2 c m₀ m' f (hS : S k), … →) and I and the trip count N took
k c m₀ m' f hS; a proof of the three repeated the thread's facts three times. Now a proof of H
is fun th => ⟨head, round, exit⟩, with the facts once, in th. The edge premise EdgeWith is in
none of them: the clause discharges it. exit's store must put bs th.k, so it links the
invariant's accumulator to the bytes the user chose.
What stays hand-written. For naive: the invariant NaiveThread.Inv with %48's
fmul contract operands, and head_in, round_in and exit_in (round_in ends with
NaiveThread.round_inv for the invariant's step). With them, NaiveIn.runIn is one term of
naive.runInv at I j W := Inv (oN c 0) (pairs A B r c K) j W ∧ W.prods %48 = none and
⟨head_in …, fun … => round_in …, fun … => exit_in …⟩ (NaiveIn imports NaiveSound;
no cycle: NaiveSound imports only NaiveSpec and the command). The facts at a loop head that the
invariant carried before (one structure of thirteen facts: the function, the buffers, Elem,
Elem.Only and the registers the loop keeps) are the clause's Mat.Head and naive.kept,
below; the structure is deleted.
It needs neither entry_in nor thread_run: the clause discharges the first and the library
theorem replaces the second. NaiveKernel.correct stays naive_sound at NaiveIn.runIn, two
lines. It could also be naive.sound_inv at fun th => ⟨…⟩, the same three theorems at
NaiveSpec.At.of_entry of th.entry once; that is ten lines, and the repack At.of_entry is
already naive_sound's.
Tests (MojoProofTest/NaiveSound.lean, section Clause):
- an open-goal test (
#guard_msgs) ofnaive.sound_invatfun th => ⟨?head, ?round, ?exit⟩showscase headwith the one hypothesisth, andcase roundandcase exitwiththand the head of roundi(ormax K 0) asR^[i] V₀with its context, step count,Mat.HeadandI, at every launch and memory ofMat.Preat naive's constants; - four refusals: a chain whose loop has a nested loop (
naiveN,naiveLwith itself as its nested loop), two chains (naiveT,[chainN, chainN]), a clause name that is a binder name ofn.runInv(naiveI, the output namedI), and a chain whose entry obligations have one more condition thatmojo_oblcannot prove (naiveE, that register 0, the struct parameter%0, is a word; the checker accepts extra obligations after the block's own,coversWith's prefix test). For the last, the messages of the failed attempt (mojo_obl's open goal, the elaborator's) are dropped, so the one message is the refusal's, which ends with the first error's goal without its hypotheses (⊢ Cond.Holds (Valuation.entry c 0 m' f) … (Cond.bool (SVal.reg 0))); naive_bases:LoopSeg.bases naive.fn_0 naiveL = [11, 12]bydecide +kernel, the registers the clause evaluates and through whichnaive.runInvprovesMat.Headat every head.
Tests (MojoProofTest/NaiveKeep.lean): two twins of naiveL, each naive.fn_0 with one block
changed ({ naive.fn_0 with blocks := … }), and the refusal n.runInv does not elaborate at
each (#guard_msgs):
fnK: the address ofA's element (%56to%59) is computed in the body%50, so the latch's load%60reads through%59, a register the loop does not keep.LoopSeg.basesis[12]andLoopSeg.loadsFromat it is false (loopK_bases); the command evaluates it before the attempt, and the refusal namesMat.Head.iterate's premiseLoopSeg.loadsFrom,%12and the block%52whose load reads through a pointer whose base is not a register the loop keeps.fnO: the latch's address%59is in the output's pointer%10instead ofA's%11. The loop keeps%10,LoopSeg.basesis[10, 12]andLoopSeg.loadsFromholds at it (loopO_bases), but%10at the loop head names the output's block: the refusal namesMat.Head.iterate's premise onLoopSeg.basesat%10, whose value neither conjunct ofhneshows to name a block other than the output's, with the goal⊢ bC ≠ bC.
Open questions.
roundasks forRoundWithat every head of a round. For naive that isOblMatmul.naive_rounds, bymojo_oblat symbolic registers. The design for the clause to prove it is in the next section; it is not built.C.loops = [L]with no nested loop covers naive, but not a kernel with two loops in sequence or nested ones.ChainWith.loopcovers them, with one invariant per loop.
The heads of the rounds (LoopIterWith, Mat.Head)
The problem. LoopInvWith.round asks for a round's RoundWith at every valuation W where
the invariant holds. RoundWith reads the registers the loop keeps (for naive the pointers %11
and %12, the bound %16 and the row and column offsets %26 and %37) and the memory facts
of its loads (the buffers of A and B), and exit reads the output's buffer, Elem and
Elem.Only. An arbitrary W of the invariant says nothing of them, so the invariant had to
carry them all: thirteen facts in one structure, which head_in proved at the loop head and
round_in again after every round. But the heads of the rounds are not arbitrary: they are the
iterates R^[i] V₀ of the round R = Valuation.roundWith contract L.h L.H L.B from the loop
head's entry valuation V₀ = Valuation.roundWith contract l S E V, and the library already
proves what a round keeps at an iterate, for every program:
LoopSeg.kept_roundandValuation.iterate_regs_keep(Sym/LoopFacts.lean): the registers the loop keeps (LoopSeg.kept) have their values atV₀;Valuation.iterate_blocks,Valuation.iterate_elemandValuation.iterate_only: if the loop path reads memory only through kept registers (LoopSeg.loadsFrom), every block,ElemandElem.Onlyare as atV₀(Mem.Buffer.of_block,Mem.Fits.of_block,Mem.Holds.of_blockfor the buffers).
The library (Sym/KernelIter.lean, for every program and every loop):
structure LoopIterWith (contract : Bool) (L : LoopSeg) (V : Valuation) (l : Nat) (S : Summary)
(E : List (Nat × List Cond × Summary)) (Q : Mem → Prop) (n : Nat) (F : Valuation → Prop)
(I : Nat → Valuation → Prop) : Prop where
head : I 0 V₀
round : ∀ i < n, (R^[i] V₀).ctx = V.ctx → (R^[i] V₀).k = V₀.k + i * (pathLen L.H L.B + 1) →
F (R^[i] V₀) → I i (R^[i] V₀) →
RoundWith contract L.h L.p L.dh L.H L.B (R^[i] V₀) ∧ I (i + 1) (R (R^[i] V₀))
exit : (R^[n] V₀).ctx = V.ctx → (R^[n] V₀).k = V₀.k + n * (pathLen L.H L.B + 1) →
F (R^[n] V₀) → I n (R^[n] V₀) → RetWith contract (R^[n] V₀) Q ((L.h, L.dh, L.H) :: L.X)
theorem RetLsWith.of_iter (hL : L.inner = []) (hE : EdgeWith contract L.h L.p V l ds S E)
(hF : ∀ i, F (R^[i] V₀)) (H : LoopIterWith contract L V l S E Q n F I) :
RetLsWith contract Q [L] V l ds S E
(V₀ and R written out in the source.) LoopIterWith.toInv gives LoopInvWith at the
invariant W = R^[i] V₀ ∧ I i W, and RetLsWith.of_iter is RetLsWith.of_inv at it. Mat.Head prog fn t enc al o a b sC x y w cell bs k m₀ T W is
the facts at a valuation of a matmul kernel that rounds which only read keep: W.fn = fn, the
three buffers of Mat.Entry on W.mem, Elem m₀ o w cell bs k W.mem and
Elem.Only o T W.mem. Mat.Head.iterate proves it at every R^[i] V from V, when
L.loadsFrom fn rs and each register of rs at V names only blocks other than o.
LoopSeg.bases fn L is the rs to use: the kept registers through which some load of the loop
path reads.
The clause. n.runInv takes F = Mat.Head … at the thread and proves hF: Mat.Head at
V₀ by mojo_inv (the function, the buffers and Elem, Elem.Only through the path in, from
Mat.Entry, hE and hO), then Mat.Head.iterate at rs = LoopSeg.bases fn Lp, evaluated
when the command runs ([11, 12] for naive), with L.loadsFrom fn rs by decide +kernel and
each r ∈ rs at V₀ by n.kept at round 0 (by obl_have where n.kept states it by its value
at V₀), a pointer to a or b, which differ from o (hne).
Deliberate restatement of n.runInv and n.sound_inv. Old, at LoopInvWith:
n.runInv : ∀ {L} (hL : L.Valid) … (hsz) {k q0 q1 q2 c m₀ m' f} (hS : S k) (h : Mat.Entry …)
{I N} (H : LoopInvWith c₀ L₀ V C.l C.S C.E Q N I), ∃ C ∈ chains, RetLsWith c₀ Q C.loops V …
n.sound_inv : … {I N} (H : ∀ th, LoopInvWith c₀ L₀ (V th) C.l C.S C.E (Q th) (N th) (I th)) →
Kernel.Sound …
New, at LoopIterWith with Mat.Head:
n.runInv : ∀ {L} (hL : L.Valid) … (hsz) {k q0 q1 q2 c m₀ m' f} (hS : S k) (h : Mat.Entry …)
(hne : a ≠ o ∧ b ≠ o) (hE : Elem m₀ o w cell bs k m') (hO : Elem.Only o S m')
{I N} (H : LoopIterWith c₀ L₀ V C.l C.S C.E Q N (Mat.Head … k m₀ S) I),
∃ C ∈ chains, RetLsWith c₀ Q C.loops V …
n.sound_inv : … {I N}
(H : ∀ th, LoopIterWith c₀ L₀ (V th) C.l C.S C.E (Q th) (N th) (Mat.Head … th.k th.m₀ S)
(I th)) → Kernel.Sound …
n.runInv gains hne, hE and hO, which Hin gives every thread and which n.sound_inv
passes from Mat.Thread; its premise H is weaker (its round and exit at the iterates only,
with Mat.Head there). n.sound_inv's premise is weaker in the same way, with the same
binders. The old n.runInv is not a corollary of the new one, which needs hne, hE and hO;
both theorems are generated per kernel, and no proof used the old ones after NaiveIn.runIn
moved, so this is a deliberate restatement. LoopInvWith stays the library form for an
invariant at every valuation: LoopIterWith.toInv gives it from LoopIterWith and F at every
iterate, and RetLsWith.of_iter is RetLsWith.of_inv at it.
The trip count, restated. n.runInv's binder {N : Nat} and n.sound_inv's
{N : Mat.Thread … → Nat} are gone, and LoopIterWith's trip count is max K 0 in both (K
the clause's third size):
-- before
n.runInv : … {I N} (H : LoopIterWith c₀ L₀ V C.l C.S C.E Q N (Mat.Head … k m₀ S) I), …
n.sound_inv : … {I N}
(H : ∀ th, LoopIterWith c₀ L₀ (V th) C.l C.S C.E (Q th) (N th) (Mat.Head … th.k th.m₀ S)
(I th)) → Kernel.Sound …
-- after
n.runInv : … {I} (H : LoopIterWith c₀ L₀ V C.l C.S C.E Q (max K 0) (Mat.Head … k m₀ S) I), …
n.sound_inv : … {I}
(H : ∀ th, LoopIterWith c₀ L₀ (V th) C.l C.S C.E (Q th) (max K 0) (Mat.Head … th.k th.m₀ S)
(I th)) → Kernel.Sound …
The new theorems are the old ones at N := max K 0, so they follow from them; the old ones do
not follow from the new. What the restatement buys is round's premise i < max K 0, the bound
that the header's %49 compares with %16 = smax(K, 0): a proof inside the command (step 3
below) can use it, which it cannot for a trip count that is a binder. At naive, max K 0 is the
length of pairs (K ≤ 768), the trip count NaiveIn.runIn inferred before, so round_in
takes i < max K 0 as it is and exit_in reads %47 = max K 0 off the invariant. N is no
longer a binder name that the clause refuses (matInvBinders).
What is left to the user, for naive (MojoProofTest/NaiveIn.lean):
- the invariant, now
Inv (oN c 0) ps j W ∧ W.prods %48 = none(the counter%47, the accumulator%48over the firstjpairs, and%48with nofmul contractoperands); head_in: the invariant atV₀, three lines (obl_haveand mojo_inv);round_in: the round'sRoundWith(OblMatmul.naive_roundsatnaive.kept's registers andMat.Head's buffers), the float step of%48and the counter, and the invariant after it byNaiveThread.round_inv, 30 lines;exit_in: the path out with the store of the accumulator (OblMatmul.naive_exit,Elem.apply_store,Elem.Only.apply), with%40fromnaive.keptand its value atV₀by mojo_inv, 36 lines;length_pairs: the length ofpairsismax K 0forK ≤ 768, two lines;runIn, one term ofnaive.runInv, six lines.
Hand-written proof lines of the theorems of NaiveIn.lean: 75 before, 81 after (head_in 7 to
3, round_in 27 to 28, exit_in 35 to 36, runIn 6 to 8, kept 6 new); NaiveThread.lean 126,
unchanged; NaiveSound.lean 40 to 41 (naive_bases, LoopSeg.bases at naiveL is [11, 12],
one line). The library adds 22 lines for every program (LoopIterWith.toInv
8, RetLsWith.of_iter 1, Mat.Head.iterate 13). The invariant is smaller (two facts instead of Head's thirteen
besides Inv), but the per-kernel proof lines did not drop: round_in and exit_in still
prove the round and the path out, and now ask for the registers the loop keeps instead of
reading them from the invariant. With the generated naive.kept (below) the count is 83: kept's six lines
go, round_in is 29 (the call of naive.kept takes two lines) and exit_in 43 (%40, whose
value naive.kept leaves as the one at V₀, by mojo_inv at V₀ with At's bounds, six lines
more). The elaboration of the four theorems is about 118,000 (#count_heartbeats,
in thousands) instead of 164,000 (round_in 76,581 instead of 114,321, head_in 5,992 instead
of 37,855); round_in has no simp on its hypothesis hj, only the cheap one on hlen.
On scratch copies, simp only [pairs, List.length_take, List.length_ofFn] at hj adds about
2,900 to round_in (79,483), and about 3,000 to the previous round_in (117,299). With the
trip count max K 0 stated by the clause (above) the count is 77 (length_pairs 2, head_in 3,
round_in 30, exit_in 36, runIn 6): round_in takes i < max K 0 as round gives it (the
length of pairs and the bound derived from it, four lines, go; round_inv is called in it, so
runIn loses two lines), and exit_in reads %47 = max K 0 off the invariant (its length of
pairs and its %47 from it, seven lines, go); the one length fact left is length_pairs, for
round_inv's j < ps.length.
The registers the loop keeps, n.kept. The clause adds n.kept: for every launch valid,
sizes below 2 ^ 31, thread in bounds with Mat.Entry, count i and head W = R^[i] V₀, each
register of LoopSeg.kept (evaluated in the command; at naive %16, %26, %11, %37, %12,
%40) has at W the value that obl_have computes at V₀, with the thread's index as
Launch.index. The proof is LoopSeg.kept_round at each (decide +kernel), with
V₀.fn = fn by mojo_inv.
The launch's validity is a premise because obl_have needs it for %26 and %37 (the sext
of ntid). Where obl_have gives a value only as a Classical.choose, the statement is the
register's value at V₀ itself: at naive %40, the address of the thread's cell, which
obl_have computes with At's bounds m * 50257 < 2 ^ 31 and n ≤ 50257 (on a scratch copy)
and which the clause's facts do not bound (the stride 50257 is a constant of the IR;
Mat.Entry's sC is a binder not tied to it). The command
elaborates the theorem once, finds those registers in its statement, and elaborates it again with
them stated so. The command adds n.kept before n.runInv, and n.runInv's proof takes
Mat.Head.iterate's premise from it: each register of LoopSeg.bases has at V₀ the value of
n.kept at round 0 (W := V₀, rfl), one projection of its conjunction, which names a block
other than the output's by hne; obl_have at V₀ is left only for a register that n.kept
states by its value at V₀. At naive LoopSeg.bases is %11, %12, both from n.kept.
NaiveIn.kept is deleted; the test in MojoProofTest/NaiveSound.lean states naive.kept's six
values. The n.kept does not elaborate refusal has no test: at naive the
clause's facts give a value or a Classical.choose for every kept register.
Not built: the round's RoundWith by mojo_obl in the clause. With the registers the loop
keeps and Mat.Head at every head, the round's obligations at naive read, besides them, the two
phis (%47, %48) and the scalar facts (K ≤ 768, m * 768 and n * 768 below 2 ^ 31, the
counter below smax(K, 0)). The plan:
- The clause's
roundpremise becomes the invariant's step alone: at the head of roundiwithF,I iandRoundWith,I (i + 1)after it; the clause provesRoundWithatR^[i] V₀. - For that the phis must be hypotheses
mojo_oblfinds by type, so the invariant is split into the phis' values as terms of the clause,W.regs r = some (v i)for each phirof the header (for naive%47 = iand%48the accumulator's encoding), and the user's restI.vis a binder of the generated theorems, asIis (a clause term about the tensors does not type inn.sound_mat, above). - The kept registers at
R^[i] V₀fromn.kept(built, above); the counter's boundi < Nfromround's premise. The scalar facts are not the clause's:Mat.Entryandhszgive the sizes below2 ^ 31, and the IR's strides (768, 50257) are constants of the program, notMat.Entry'ssA,sB,sC, soK ≤ 768andm * 768 < 2 ^ 31are not among the clause's facts, as%40's value shows (n.keptleaves it as the value atV₀); the command would read them from the IR's constants and state them as a premise (below). mojo_oblonRoundWithatR^[i] V₀, and if it leaves a goal, a refusal naming it (mojo_kernel: mat: inv: the round's RoundWith at the head of round i is not discharged by mojo_obl: <goal>), with a#guard_msgstest at a twin ofnaiveLwhose body loads through a register the loop does not keep.
How steps 2 and 4 would get K ≤ 768 and m * 768 < 2 ^ 31 as clause facts. They are facts
about the IR's constants: naive's entry path computes %26 = mul i32 %25, 768 and
%37 = mul i32 %36, 768 (the row %25 and the column %36, truncs of the thread's 2-D index,
times 768), two registers the loop keeps, and the body adds the counter's trunc %56 to them
(%57, %61) before the sext of each load's index. The mojo_kernel … mat … inv command
(elabMat, MojoProof/Sym/KernelCmd.lean) would read the constant where it evaluates
LoopSeg.bases: for each register of LoopSeg.kept whose node in the summary of the chain's path
into the loop (C.S.nodes) is SNode.bin .mul _ 32 a (.int 32 s), with a the trunc of the
thread's row (bounded by m, hX) or column (by n, hY), it takes s. It would then state,
with the constants as numerals, after hsz in n.runInv and n.sound_inv
(hdim : K ≤ 768 ∧ m * 768 < 2 ^ 31 ∧ n * 768 < 2 ^ 31)
(K ≤ s once for each constant s, and m * s or n * s for each register by the index it
multiplies; m, n, K are the clause's size binders). In step 4, obtain ⟨hK, hm, hn⟩ := hdim
before mojo_obl, as for hsz today, gives by type with step 2's phi value
W.regs %47 = some (.bits 64 (BitVec.ofNat 64 i)) and the header's %49 (i < smax(K, 0)) the
i32 range of %57 = r * 768 + i and %61 = c * 768 + i (below m * 768 from r < m and
i < K ≤ 768). A caller proves hdim at the instance: naive's At.dims
(MojoProofTest/NaiveSpec.lean) has the three conjuncts, which MojoProofTest/NaiveIn.lean already
passes to OblMatmul.naive_rounds. A kept register of another shape gives no conjunct, and
step 4's refusal names the goal left open.
It is not built because step 2 changes what the user states (the phi values as functions of the
round, with the accumulator's float step) and step 4 elaborates mojo_obl on the whole round at
symbolic registers inside the command, at naive the work of OblMatmul.naive_rounds; neither
fit this change with its test. round_in would then keep only the float step of %48 and the
counter; kept is already the clause's. The twin of step 4 is built (fnK,
MojoProofTest/NaiveKeep.lean, above): today the clause refuses it before any round, at
Mat.Head.iterate's premise LoopSeg.loadsFrom, with the refusal of n.runInv.
Two more things the steps need from elabMat. Step 3's bound on the counter is i < smax(K, 0)
(the header's %49 compares it with %16 = smax(K, 0)): it is round's premise, since the trip
count of LoopIterWith in n.runInv and n.sound_inv is max K 0, which the command states
(above). The trip count is the third size's, not read from the loop's bound register: for a loop
over another count (a tiled loop over K / t) H does not hold, and stating the trip count from
the register that the header compares the counter with, as n.kept gives it, is not built.
n.kept is added before n.runInv and used in its proof (above), so its values are a
declaration when n.runInv's proof would run mojo_obl on the round.
hdim stated without steps 2 and 4 would be a premise no proof uses, so it is not stated yet.
Through collective calls: Seq.ToWait and its fire
Lean: MojoProof/Sym/SchedWait.lean, on Turns (MojoProof/Sym/Sched.lean); instances and twins:
MojoProofTest/SymWait.lean and MojoProofTest/SymColl.lean. The statements in "Proved" hold for every program, launch and
contexts; "Not built" is a plan, not a proof.
The schedule: each thread of the grid in turn runs alone to its next wait, a call of the barrier
or of a warp shuffle (step gives .wait, and Grid.advance sets the thread's status to
.wait); the collectives then fire (Grid.fire, which resumes each participant with the call's
value under the callee's return attributes, resumeAll and Thread.resume; a shuffle's lane
reads the lane shflSource names); and each thread, resumed, runs on in turn. The values the
collectives deliver are the semantics', not a model of them.
Proved.
Turns R ns m Es m': threadsnsin turn, each by the runR nfrom the memory the one before it left.Seq(runs to the end) is now defined asTurnsofRuns(anabbrev; it was an inductive of the same two constructors), andSeq.grid,Seq.trace,Seq.of_invareTurns.grid,Turns.trace,Turns.of_invat it.Turns.grid: when each turn is a run of grid steps that sets threadn's status tos n, the turns are a run of grid steps to the grid with each of the distinct threadsnsats n(foldl_set_getElem?,foldl_set_size).ToWait c t m (.wait u i as d) m': steps that continuet(Steps), touonm', then the step that waits at intrinsiciwith argumentsasand calleed.ToWait.grid: a run of grid steps to the grid with the thread waiting;ToWait.trace.Seq.ToWaitisTurnsofToWait, withSeq.ToWait.grid;Turns.of_invwithToWait.tracegives one by an invariant.runTocomputes a thread's steps to its first step that does not continue it;ToWait.of_runToandRuns.of_runToturn one that ends at a wait or a return into aToWaitor aRuns(runTo_steps).- The segment form (MojoProof/Sym/Segment.lean):
Seg.soundends at a collective withWaits, which contains aToWaitto the call (Waits.toWait; at gemv_kernel's first segment,SymWait.gemv_toWait);Seg.throughtakes the deliveriesw : Nat → Option Val × Mem(the call's value and the memory the thread resumes on) as inputs, for everyw, andSeg.Through.toWaitsplits its run at the first collective into aToWaitand the run of the other segments from the thread resumed with(w 0).1on(w 0).2. A schedule pickswafter the fact: at a barrier(w 0).1 = noneand(w 0).2is the memory the schedule reaches when the thread resumes. Grid.fire_barrier: when every threadkof blockbwaits, fromu k, at the barrier with one number below 16 and at the instructionu (b * volume L.block)is at, the fire by the block's first thread resumes each with no value and logs.barrier b.Grid.fire_barriers: the barriers of blocks0toB - 1fired in turn, a run of grid steps (resumeAll_eq,mem_block).Grid.fire_shfl: when every lanejof threadn's warp (warpLanes) waits at a shuffle of one mode with the full member mask, lane operandb jand clampcl j, at one instruction, and the callee's return attributes take laneshflSource mode j (b j) (cl j)'s value (shflVal,poisonfor a lane outside the warp) tor j, the fire resumes each lane withr j; the memory is unchanged.Seq.start_sound_bar: a start (Grid.start,Grid.start_size) whose threads run in turn to one barrier (Seq.ToWait), each block's threads at one number below 16 and one instruction, and then, resumed with no value, in turn to their ends from the memory with the blocks'.barriers logged (Seq), with a trace that has no race and keeps the promise of!invariant.loadand an observation meetingR, is sound (Grid.Sound), with blocks ofvolume L.block > 0threads. BySeq.ToWait.grid,Grid.fire_barriers,Seq.grid,Grid.done_foldl,Grid.Done.bad_iffandGrid.start_sound.
The instances (MojoProofTest/SymWait.lean): sound is Seq.start_sound_bar on Launch.k
(alloca, store, the barrier, ret) launched on one block of two threads, with the runs
runTo computes; bar_twin: with one thread of the block not at the barrier the fire does not
complete; shfl2_fire is Grid.fire_shfl on two lanes at a butterfly shuffle, each resumed
with the other's value; shfl_twin: with the lanes at shuffles of different modes the fire
faults.
Proved: a schedule of several collectives.
Fires L c N s m t' m', a phase's collectives: from every grid ofNthreads at the statusesson memorym, grid steps reach a grid ofNthreads runningt'onm'.Fires.barriers: the barrier phase, for every launch with blocks ofvolume L.block > 0threads andN = B * volume L.block(Grid.fire_barriers; the threads resumed with no value, the blocks'.barriers logged in turn).Fires.shfls: the shuffle phase, for every mode and every suchN, with the full member mask, lane operandb nand clampcl n(Grid.fire_shflat every warp's first lane in turn; threadnresumed withr n, what its callee's return attributes give to the operand of laneshflSource mode (n % volume L.block % 32) (b n) (cl n)of its warp; the memory unchanged).Sched L c N t m m', a list of phases: the threads in turn to their waits (Seq.ToWait), the phase'sFires, the schedule from the resumed threads; the last phase runs them in turn to their ends (Seq).Sched.grid: a run of grid steps to a done grid with memorym'.Sched.start_sound: a start (Grid.start,Grid.start_threads) with a schedule whose last memory's trace has no race, keeps the promise of!invariant.loadand observesywithR yis sound (Grid.Sound).Seq.start_sound_bar(item 6) is now its one-line case at one barrier phase,Sched.waitofFires.barriersandSched.ends.bflyRoundsAt_of_shfl: for every combinationF r lper round and lane, width2 ^ kwithk ≤ 5, list of offsets below2 ^ k, familyv r lof lane values by round and first valuesw: ifv 0 l = w land each round's value of lanelcombines, byF r l, its own with that of laneshflSource .bfly l ms[r] 31(shflSource_bfly:l ^^^ ms[r]), the lanes below2 ^ khold after the roundsbflyRoundsAt F ms w l; with one combining operation,F = fun _ _ => combine, that isbflyRounds combine ms w l.Seq.ToWait.of_runToandSeq.of_runTo: whenrunTotakes each threadk < Nin turn frommem kto a wait (or to its end) with memorymem (k + 1), the threads in turn reach their waits (or their ends) frommem 0tomem N(Turns.of_inv,Seq.of_inv).
The instance (MojoProofTest/SymColl.lean): a hand-built kernel (tid.x, a barrier, two
butterfly shuffles at offsets 1 and 2, each followed by an add, ret) on one block of 4
threads. sound is Sched.start_sound with the three phases (Fires.barriers, then
Fires.shfls twice, each lane resumed with shflSource's lane's value) and the ends, with the
runs runTo computes and the kernel's evaluation (kernel_rfl, MojoProofTest/KernelRfl.lean);
lanes: each lane holds in %4 bflyRounds (· + ·) [1, 2] (fun l => l) l, by
bflyRoundsAt_of_shfl at the registers %0, %2, %4, which is 6 (lanes_six). The open-goal
twin (#guard_msgs) leaves the second shuffle's Fires as the goal when its fire is missing.
The schedule from the threads' segments. Lean: MojoProof/Sym/SchedChain.lean, for every program, launch and contexts; tests in MojoProofTest/SymChain.lean.
- Phases by invariants. A thread of a kernel with collectives is a chain: a run to the first
collective, the collective, a run from the resumed thread to the next one, and last a run to
its end.
Sched's premises are about threads and memories the schedule reaches, which a proof does not compute; so the theorem takes, for phasej, a predicateT j non threadn's thread,W j non the status it waits at andP j kon the memory afterkthreads have run the phase, and asks: each thread ofT j nfrom a memory ofP j nruns to a wait ofW j nleaving a memory ofP j (n + 1); from statuses ofW j non a memory ofP j Nthe phase's collectives fire (Fires) to threads ofT (j + 1) non a memory ofP (j + 1) 0; in the last phaseJeach thread runs to its end.Seq.ToWait.of_inv(each thread's status is chosen by its own run, so the statuses are built thread by thread),Sched.of_inv(by induction on the phases left) andSched.start_sound_inv(Sched.start_soundat the start's threads,Grid.start_threads, with the trace and observation premises on every memory ofP J N). One theorem for every chain: any number of phases, any collectives. - The fires from the statuses' facts.
Fires.barriersandFires.shflstake the waiting threads and arguments as functions; a phase ofSched.of_invgives a predicate on each status.Fires.barriers_at: when every thread's status is a wait at the barrier with its block's number below 16, at its block's instruction, the barrier phase fires, each thread resumed with no value.Fires.bfly: when every thread waits at a butterfly shuffle with the full mask, offseto < 32, clamp 31, offeringA n, at its warp's instruction, with a callee whose return attributes keep the value, and the lane it reads is in its block, each threadnis resumed with the value of threadn - p + (p ^^^ o)(pits lane): the valuesbflyRoundsAt_of_shfltakes. - The runs from the segments.
Seg.throughgives a thread's chain for every deliveryw; a schedule knows the delivery only after the phase.Seg.Through.wait: from the chain for every delivery and the first segment's obligations, the run to the first collective (ToWait) at the instruction(f.fn.name, lbl, f.pc + S.len), the registers and the arguments the summary gives, and, for every delivered value and memory, the chain of the other segments from the resumed thread, for every later delivery (ToWait.det: the run to the wait does not depend on the deliveries). So threads at one block and position wait at one instruction, the premise of both fires. - Values through the shuffles: after the five rounds at offsets 16, 8, 4, 2, 1, lane
l's value isbflyRoundsAt F warpOffsets v lof the lanes' first valuesv, when each round's value combines the lane's with the delivered one byF r l, a combination per round and lane, such asfaddat each lane's own oracle numbers (bflyRoundsAt_of_shfl). - Instances: the hand-built kernel of MojoProofTest/SymColl.lean (
tid.x, a barrier, butterfly shuffles at offsets 1 and 2,ret) on one block ofkthreads,k = 4andk = 8, in one proof (SymChain.sound_inv):Sched.start_sound_invat three phases, the invariants being equations with the threads, statuses and memoriesrunTocomputes (ph,stat,memAt), the fires byFires.barriers_atandFires.bfly. The open-goal twin (#guard_msgs) leaves the second shuffle'sFiresas the goal when its fire is left out. - Not built: gevm_kernel's
%59phases (barrier and shuffles) from MojoProofTest/OblGevm.lean's segments. Each thread's run before%59is a premise there.RunsVia's waits state the instruction a thread waits at (Thread.at), which both fires need:OblGevmThread.threadgives statement 6 of%59for the barrier and 11, 15, 19, 23 and 27 for the shuffles.