Skeleton transfer, the output term and payload relations (T3, T4, T5)
Status. T3a is proved as stated below, for every launch, contexts and relation
(MojoProof/Sem/Lockstep.lean; instance and twin in MojoProofTest/Lockstep.lean). T3b's relations on
values, memory, threads and grids (Val.erase, Val.Skel, MemByte.erase, MemByte.Skel,
Block.SkelEq, Mem.SkelEq, Labels, Labels.Rel, Frame.Skel, Thread.Skel, Thread.payRes,
Intrinsic.eraseArgs, Status.Skel, Grid.SkelRel; Val.Skel, Mem.SkelEq, Thread.Skel,
Status.Skel and Grid.SkelRel reflexive and symmetric) are stated in MojoProof/Sem/Skeleton.lean,
with the instances skel_vals, skel_pay, skel_thread and skel_grid and counterexample (iii)
addr_twin (two address choices give memories that are not related) in MojoProofTest/Skeleton.lean.
So are its memory lemmas, proved for every layout, type and set of payload blocks:
Layout.encode_erase, Layout.decode_erase (for data types, Ty.data, and at most the stored
size), Mem.check_skel, Mem.load_skel, Mem.store_skel, Mem.set_skel, Mem.log_skel,
Mem.alloc_skel and Mem.setLive_skel (instances and twins decode_twins, load_skel,
store_skel, alloc_skel); evalV_skel, for every scope, type, operand and two oracles
(castV_ch; eval_skel, fpext_twin); and lanes_skel, lanes2_skel, intCast_skel,
intBin_skel, icmpV_skel, floatBin_skel, fcmpV_skel, fnegV_skel, selectV_skel,
extractE_skel, insertE_skel, shuffleV_skel, extractV_skel, insertV_skel, castV_skel,
fminmax_skel and rsqrt_skel (trunc_skel, pair_skel, bin_skel, icmp_skel, float_skel,
select_skel, elem_skel, shuffle_skel, value_skel, cast_skel, maxnum_skel,
approx_skel); and withAttrs_skel (attrs_skel). The labelling checks Labels.Ok and
Labels.MemOk (with Labels.MemOk.of_closed) are stated in MojoProof/Sem/Labels.lean (instances
and twins vadd_ok, vadd_twin, branch_twin and store_ok in MojoProofTest/Labels.lean).
exec_skel, for every statement, is proved in MojoProof/Sem/SkelExec.lean (with exec_call_skel
for calls; instance exec_inst, twins exec_twin of Labels.stmtOk, exec_mem_twin of
Labels.MemAt and exec_call_twin of Labels.Ok in MojoProofTest/SkelExec.lean). So is
enter_skel, for every block entry of a function that passes Labels.funcOk (instance
enter_inst, twin enter_twin of Labels.funcOk). step_skel, for every step of related threads
whose first's frames meet Labels.FramesOk (kept by step_framesOk), and Grid.advance_skel, for
every thread of related grids, are proved in MojoProof/Sem/SkelStep.lean, and so is
Grid.FramesOk at every grid reachable from a start whose kernel is the module's function of its
name (Grid.start_reach_framesOk) (instances step_inst, call_framesOk, advance_inst and
start_framesOk, twins ret_twin and fn_twin of Labels.FramesOk, call_framesOk_twin of
Labels.Ok and start_framesOk_twin of the premise on the kernel in
MojoProofTest/SkelStep.lean), and so is Thread.pending_skel, for every pair of related threads
(instance pending_inst, twin pending_twin of Labels.Ok), and so is Grid.fire_skel, for
every collective call of related grids whose first meets Grid.FramesOk under the one program of
all contexts and Grid.AtCalls (instance fire_inst, twins fire_atCalls_twin,
fire_prog_twin, fire_ok_twin and fire_framesOk_twin). So are Grid.start_skel, for every two
starts on related memories (instance start_inst, twin start_twin of Mem.SkelEq), and T3b
itself, Grid.skel_lockstep, for every start whose program passes Labels.Ok, whose kernel is the
module's function of its name and that meets Labels.MemOk (instance lockstep_inst), and T3 on
T3b's relation, Grid.skel_run, for every such start on the first of two related caller memories
and every run from it to a done grid that is not bad (instance run_inst, one kernel that returns
at once on memories that differ in one data byte; twin run_twin of Mem.SkelEq; and
PayloadRun.run_inst, one kernel that loads a float from the payload block, adds it to itself and
stores the sum, twin PayloadRun.run_twin). T3c on terms is proved to the end of a returning path
(sections "To the next block's entry" and "Along a path"); T4 has no Lean beyond one summary's
check (section "The term block %21 of vector_addition stores"); of T5, the rows one operation
at a time are proved (section "T5's rows"), the term statement SVal.eval_respects is not.
The proof relies on these properties of the semantics (MojoProof/Sem):
- An
alloca's addresses come fromCtx.addr(skeleton choices), andCtx.oracleholds the float freedoms only (MojoProof/Sem/Thread.lean). So no oracle position is a skeleton choice. - An
alloca's block isMem.fresh m n k = m.next + Nat.pair n k. Two runs in lockstep make the same block numbers, so no renaming is needed. - An admitted
atomicrmwleaves its result register unset (its old value depends on the order of the atomics on one location). - The threads of a collective call are matched on their position, not on a position and a count
of completed calls. A different matching would change the proof of
Grid.fire_skelbelow but not its statement: two runs in lockstep have the same positions and step counts, so one matching applies to both sides.
Scope.
- T3a: every launch, two context families and every relation.
- T3b: every program, kernel, launch, arguments and address choice, with two caller memories that
agree off a set of payload blocks and two payload oracles, for a program whose registers carry a
labelling that passes
Labels.Ok. The memory hypothesisLabels.MemOkis on the first run only. - T4: every program with a block summary of the symbolic checker (MojoProof/Sym).
- T5: every relation and every term.
Which corpus kernels pass Labels.Ok is not claimed here, except vector_addition (vadd_ok,
MojoProofTest/Labels.lean). Expected, and not checked:
tiled_matmulpasses. Its payload operations arefadd,fmulandfadd contract, and its guards and addresses come from special registers and the size argument.ln64keeps payload in{ float, float, float }aggregates, which T3b admits, and callsrsqrt.approx(82 calls in the corpus, none with fast-math flags).Op.Totallistsrsqrt.approxwithoutnnanandninf(rsqrt_skel).
A kernel that branches on payload, or computes an address from it, is outside T3. It is verified per payload and oracle by the block simulation alone; T1, T2 and T2′ still apply to it.
How the proof is organized.
- T3 is split in two:
- T3a: a lockstep bisimulation between the grids of two context families carries runs,
DoneandBad, andGrid.Soundfor observations it preserves, for every relation. - T3b: the skeleton relation
Grid.SkelRelis such a bisimulation for a labelled program.
- T3a: a lockstep bisimulation between the grids of two context families carries runs,
- Obliviousness is a labelling of the SSA registers of each function, payload or skeleton,
checked on the program text (
Labels.Ok, decidable and evaluated by the kernel).- An SSA register has one definition, so a label per register is exact.
Labels.Okchecks that guards, accesses and collective calls do not depend on payload, on registers instead of on terms. - The memory part, which payload block each access may touch, is the hypothesis
Labels.MemOkon one run. Deriving it from the block checker's access terms is not proved. - So T3b does not depend on the symbolic block checker. T3c and T4 do.
- An SSA register has one definition, so a label per register is exact.
- Payload-dependent faults: T3b admits only payload operations that are total on data words. T3c
adds the partial ones (division by payload, integer and fast-math flags on payload,
float-to-integer casts,
rangeon payload). Their domain conditions become hypotheses on both runs, stated on T4's terms. - T3 ends with what the composition uses: a run on one payload to a grid that is done and not bad
gives one on the other, so
Grid.start_soundapplies to the other (Grid.payload_run).
T3a: lockstep transfer, for every relation
Definitions
/-- Two results of a step (an `advance` or a `fire`) agree under `S`: both fault, both take no
step, or both give grids related by `S`. -/
def Grid.Agree (S : Grid → Grid → Prop) : Except Fault (Option Grid) → Except Fault (Option Grid) → Prop
| .error _, .error _ => True
| .ok none, .ok none => True
| .ok (some g₁), .ok (some g₂) => S g₁ g₂
| _, _ => False
/-- `S` is a lockstep bisimulation between the grids of launch `L` under contexts `c` and `c'`:
related grids agree on every thread's step and every collective call, are done together, have
one trace, and have a race enabled together. -/
structure Grid.Lockstep (L : Launch) (c c' : Nat → Ctx) (S : Grid → Grid → Prop) : Prop where
advance : ∀ {g₁ g₂}, S g₁ g₂ → ∀ n, Grid.Agree S (g₁.advance c n) (g₂.advance c' n)
fire : ∀ {g₁ g₂}, S g₁ g₂ → ∀ n, Grid.Agree S (g₁.fire L c n) (g₂.fire L c' n)
done : ∀ {g₁ g₂}, S g₁ g₂ → (GPUProof.Done sig (g₁, L, c) ↔ GPUProof.Done sig (g₂, L, c'))
trace : ∀ {g₁ g₂}, S g₁ g₂ → g₁.mem.trace = g₂.mem.trace
race : ∀ {g₁ g₂}, S g₁ g₂ →
(GPUProof.RaceEnabled sig (g₁, L, c) ↔ GPUProof.RaceEnabled sig (g₂, L, c'))
S is any relation. To use invariants (W1 to W5, Labels.MemOk), put them into S, for
example S x y := ReflTransGen (Grid.Step L c) g₀ x ∧ R x y. A step keeps such an S because
the step's target is reachable.
Statement
For every launch L, contexts c, c', relation S with hS : Grid.Lockstep L c c' S, and
grids with S g₁ g₂:
Grid.Lockstep.symm:Grid.Lockstep L c' c (flip S).Grid.Lockstep.step:Grid.Step L c g₁ h₁ → ∃ h₂, Grid.Step L c' g₂ h₂ ∧ S h₁ h₂, by the same thread number and the same kind of step.Grid.Lockstep.path:Path (Grid.Step L c) k g₁ z₁ → ∃ z₂, Path (Grid.Step L c') k g₂ z₂ ∧ S z₁ z₂. The converse comes fromsymm.Grid.Lockstep.bad:GPUProof.Bad sig (g₁, L, c) ↔ GPUProof.Bad sig (g₂, L, c').Grid.Lockstep.sound: for every observationobswithhO : ∀ x y, S x y → GPUProof.Done sig (x, L, c) → obs x.mem = obs y.memand everyR:Grid.Sound L c g₁ obs R → Grid.Sound L c' g₂ obs R.Grid.payload_run(the corollary T3 is used through): supposeGrid.start prog fn L args m' ch ω' = .ok (g₂, c')withm'.BytesIn m'.Known, and supposePath (Grid.Step L c) k g₁ z₁withGPUProof.Done sig (z₁, L, c)and¬ GPUProof.Bad sig (z₁, L, c). Then there is az₂withPath (Grid.Step L c') k g₂ z₂,GPUProof.Done sig (z₂, L, c'),¬ GPUProof.Bad sig (z₂, L, c')andS z₁ z₂. And for everyobsthat reads only the blocks, everyRandy, ifobs z₂.mem = some yandR y, thenGrid.Sound L c' g₂ obs R(byGrid.start_sound).
Proof
Grid.Agreeflips:Grid.Agree S a b → Grid.Agree (flip S) b a, by cases onaandb. Each field ofsymmis the flip of the field, orIff.symm, orEq.symm.step:Grid.Step L c g₁ h₁is∃ n, g₁.advance c n = .ok (some h₁) ∨ g₁.fire L c n = .ok (some h₁). In the first case, rewritehS.advance hs nwith it. Cases ong₂.advance c' nleave only.ok (some h₂)withS h₁ h₂, the others beingFalse. The fire case is the same.path: induction on the path, bystep.bad, the four disjuncts of the core'sBadatsigin turn:Faults:g₁.advance c n = .error emakesGrid.Agree S (.error e) (g₂.advance c' n), which forces.error _. The same holds forfire, and the other direction is bysymm.racyand the core'skeptatsig: rewrite bytrace.RaceEnabled: this israce.
sound, field by field. Forh₂reachable fromg₂,symm.path(throughPath.exists_iff) gives anh₁reachable fromg₁withS h₁ h₂.safe: a fault ofh₂is a fault ofh₁(bad's first case).raceFreeandkept: bytrace.progress: ifh₂is not done,h₁is not done (done). Thenh₁has a step, andstepgivesh₂one.terminates: by induction onAcc,∀ h₁, Acc (flip (Grid.Step L c)) h₁ → ∀ h₂, S h₁ h₂ → Acc (flip (Grid.Step L c')) h₂. A step ofh₂is matched by one ofh₁(symm.step), and the induction hypothesis applies to its target.determinate: ifh₂andh₂'are done, thenh₁andh₁'are done, andobs h₂.mem = obs h₁.mem = obs h₁'.mem = obs h₂'.mem(hOtwice, andg₁'sdeterminate).post:obs h₂.mem = obs h₁.mem = some ywithR y.
payload_run:pathgivesz₂.doneandbadmovez₁'sDoneand notBad. The last part isGrid.start_soundong₂'s start with the run toz₂.
The proof uses no property of the semantics beyond the definitions of Grid.Step, the core's Bad
at sig and Grid.Sound. It is the real-grid form of the miniature's CRel.step, CRel.path,
CRel.flip and payload_transfer.
T3b: the skeleton relation
Definitions
/-- `v` with every data word replaced by the zero word of its width, through vectors and
aggregates: what the skeleton sees of a value. -/
def Val.erase : Val → Val -- with `Val.eraseAll` on lists (structural, mutual)
| .bits w _ => .bits w 0
| .vec xs => .vec (Val.eraseAll xs)
| .agg xs => .agg (Val.eraseAll xs)
| v => v
/-- Payload-related values: equal but for their data words, which have one width. Pointers,
`poison` and `undef` are equal; vectors and aggregates are related element by element, at any
depth (`ln64` keeps payload in a `{ float, float, float }`). -/
def Val.Skel (x y : Val) : Prop := x.erase = y.erase
/-- A data byte becomes the zero byte; other bytes stay. -/
def MemByte.erase : MemByte → MemByte
| .byte _ => .byte 0
| b => b
/-- Payload-related bytes: equal, or both data bytes. -/
def MemByte.Skel (b₁ b₂ : MemByte) : Prop := b₁.erase = b₂.erase
/-- Blocks equal in every field but `bytes`, whose bytes are payload-related, and equal unless
`p` (the block is payload). -/
structure Block.SkelEq (p : Prop) (B₁ B₂ : Block) : Prop where
shape : { B₁ with bytes := fun _ => .undef } = { B₂ with bytes := fun _ => .undef }
bytes : ∀ i, (B₁.bytes i).Skel (B₂.bytes i)
same : ¬ p → ∀ i, B₁.bytes i = B₂.bytes i
/-- Memories equal but for the data bytes of the blocks `pay`: one `next`, one trace, and at every
number both no block or blocks related by `Block.SkelEq`. -/
structure Mem.SkelEq (pay : Nat → Prop) (m₁ m₂ : Mem) : Prop where
next : m₁.next = m₂.next
trace : m₁.trace = m₂.trace
blocks : ∀ b, Option.Rel (Block.SkelEq (pay b)) (m₁.blocks b) (m₂.blocks b)
/-- A labelling: the payload registers of each function (by name), and whether its result is
payload. -/
structure Labels where
reg : String → Nat → Bool
ret : String → Bool
Thread.Skel lab t₁ t₂ relates two threads:
- equal
k; - frames pairwise by
Frame.Skel lab: equal but forregsandprods(asBlock.SkelEq.shape, the frames with both fields cleared are equal, sofn,label,pc,allocasanddestare); - registers equal where
lab.reg fn.name r = falseandOption.Rel Val.Skelwhere it is true (Labels.Rel); prodspayload-related the same way, both operands byVal.Skel.
Status.Skel relates statuses with one constructor:
runwithThread.Skel;waitwithThread.Skel, one intrinsic and declaration, and arguments related by the label of the call's result register (Thread.payRes, the registerThread.resumesets): when it is payload, the arguments are equal afterIntrinsic.eraseArgs, which erases the exchanged value of a shuffle and nothing else (the mask, lane operand and width decide which lane a value comes from, so they are skeleton); when it is skeleton, the arguments are equal. The exchanged value is copied to some lane's result register, so a payload value may only be exchanged into a payload register.donewithdone.
Grid.SkelRel lab pay g₁ g₂ holds when the grids have the same number of threads, their statuses
are related at every number, and Mem.SkelEq pay g₁.mem g₂.mem holds.
Labels.Ok prog lab (MojoProof/Sem/Labels.lean) checks each function of prog
(Labels.funcOk) and each of its statements (Labels.stmtOk); it is a Bool, evaluated by the
kernel. An operand of function fn is skeleton when it mentions no payload register of fn
(Value.mentions (lab.reg fn.name)); a constant is skeleton.
- (O1) Every operand that decides control or an address is skeleton:
condBrandswitchconditions, andselectconditions;- the pointer operands of
load,storeandatomicrmw,getelementptrbases and indices; allocacounts,extractelementandinsertelementindices,shufflevectormasks;- the arguments of intrinsic calls (
lifetime.*, collectives, special registers), but ashfl.sync's exchanged value (its second argument) and the operands ofmaxnum,minnumandrsqrt.approx; - arguments for skeleton parameters of defined functions ((O4)).
- (O2) A statement with a skeleton result has skeleton operands and reads no payload choice
(
Scope.ch): it is notfadd,fsub,fmul,fdiv,frem,fpext,fptrunc,maxnum,minnumorrsqrt.approx.fneg,fcmpand the other casts read no oracle number (Thread.lean, Eval.lean), so they may have skeleton results on skeleton operands. -
(O3) A statement with a payload result has operands that are registers or skeleton (
TValue.payOk; LLVM's constants hold no register, so a vector or constant expression with a payload register is not LLVM), and is one of:add,sub,mul,and,or,xor,shl,lshr,ashr,udivanduremwith flags ofBinOp.total(nonsw,nuw,exactordisjoint), the shift amount or divisor skeleton (BinOp.skelB);fadd,fsub,fmul,fdiv,fnegandfcmpwithoutnnanandninf(nsz,arcp,afnandreassocfault on both sides,FastMath.check;fremfaults on both, Op.lean);- every
icmp, cast,select(on a skeleton condition),phi,extractvalue,insertvalue,extractelement,insertelementandshufflevector, with skeleton operands where (O1) asks; maxnum,minnumandrsqrt.approxwithoutnnanandninf;- a
shfl.sync, a call to a defined function, an intrinsic call on skeleton arguments, anallocaor agetelementptr, whose results are related as their operands are skeleton; - a
loadof a data type (Ty.data: integers of whole bytes and floats, through vectors, arrays and structs).Layout.decodereads ani1from one byte and givespoisonfor a number of 2 or more, so for ani1whether the result ispoisonwould depend on the payload. This is the only place a data type is required:Mem.load_skel's premise. Payloadicmpandfcmpresults arei1words, related byVal.Skel(icmpV_skel,fcmpV_skel).
rsqrt.approxis in the list becausersqrtis total: it returns a word on every operand and oracle number, the oracle's if it meets the contract, else the fallback. So on two 32-bit words it gives two floats (rsqrt_skel). Undernnanorninfwhether it givespoisondepends on its operand, so those flags fail (T3c). Aggregates are admitted becauseln64keeps payload in a{ float, float, float }.The property that defines the list: on operands related by
Val.Skel, for every two oracle numbers, the operation faults on both sides or on neither, and its results are related byVal.Skel.Val.Skeloperands have theirpoisonandundeflanes at the same places, sopoisoncomes out at the same places too; a data word gives a data word for every oracle number (floatBinbyexists_deliver, Float.lean). An operation for which this fails is not in the list. These flags break it:or disjointoni8gives 3 on (1, 2) andpoisonon (1, 1);fadd nnangives a word on (0, 0) andpoisonon (NaN, 0). A shift amount of at least the width givespoison, and a divisor of 0 faults, so those operands must be skeleton.sdivandsremfault on the minimum divided by -1, which reads both operands, so they go to T3c.A
selecton a payload condition (fcmpthenselect, as in a NaN-aware maximum) is excluded by (O1): if the condition differed, the two runs would pick different operands, and one of them might bepoison. Admitting it, with a flag for payload registers that are neverpoison, is left to T3c. -
(O4) Labels agree across calls and returns:
- a payload argument of a defined function goes to a payload parameter (an argument past the
parameters is skeleton), and a call to a function with a payload result (
lab.ret) has a payload result register; - the arguments of a call to a function the module does not have are registers or skeleton
(
execevaluates them before it refuses the call); a call of inline assembly passes (execrefuses it before it evaluates anything), and a call through a pointer has no form in the AST (Callee), as the parser refuses it; - a
retof a payload operand is in a function with a payload result; - a stored value, a payload argument and a returned payload operand are registers or skeleton
(
TValue.payOk, as in (O3)); - payload parameters and results have no
rangeattribute (whose test reads the value), and neither has the declaration of amaxnum,minnumorshfl.syncwith a payload result (withAttrsinexecandresumeAll; a waiting shuffle's arguments are related only up to its exchanged value, so its result is checked whenever it is payload).
The kernel's parameters need no condition: the two runs take the same arguments, so payload enters through memory.
- a payload argument of a defined function goes to a payload parameter (an argument past the
parameters is skeleton), and a call to a function with a payload result (
Instances and twins (MojoProofTest/Labels.lean): vector_addition passes Labels.Ok with %25,
%27 and %28 payload (vadd_ok); with the stored pointer %29 payload too it fails (O1), and
with %28 not payload it fails (O2) (vadd_twin). A condBr on a payload register fails
Labels.Ok, and two frames related by Frame.Skel whose condition holds 1 and 0 step to
different blocks, so the threads after are not related (branch_twin). A store of a vector that
holds a payload register fails Labels.Ok (payOk_twin; the AST of <i8 %0>, which is not LLVM
IR and which the parser refuses).
Labels.MemOk lab pay L c g₀ holds when every grid that launch L with contexts c reaches from
g₀ meets Labels.MemAt at each running thread's next statement (Labels.MemAll):
- a
loadwith a skeleton result reads a block outsidepay; - a
storeof a payload operand writes a block inpay; - an
atomicrmwwith a payload operand updates a block inpay.
An alloca needs nothing: pay names blocks to be made too, and a store of payload into the new
block must then be in pay. Labels.MemOk.of_closed gives it from a set of grids that holds
g₀, is closed under Grid.Step and meets Labels.MemAll at each grid. Instance and twin
store_ok: a grid of one thread that stores the payload register 0 to block 1 meets it with block
1 payload, for every launch, and not with no block payload.
pay is fixed for the run and names blocks to be made too: Mem.fresh numbers them, and those
numbers are the same in both runs. The blocks of a buffer the caller gives hold payload if pay
says so; byval copies hold pointers and sizes, so they are skeleton.
Statement
For every program, kernel, launch, arguments, address choice ch, labelling lab with
Labels.Ok prog lab, payload blocks pay, caller memories with Mem.SkelEq pay m₁ m₂, and
oracles ω₁, ω₂:
Grid.start_skel(proved):Except.Rel (fun r₁ r₂ => Grid.SkelRel lab pay r₁.1 r₂.1 ∧ ∀ n, r₂.2 n = { r₁.2 n with oracle := (r₂.2 n).oracle }) (Grid.start prog fn L args m₁ ch ω₁) (Grid.start prog fn L args m₂ ch ω₂): both starts fault, or both give related grids and contexts that differ only in their oracles.Grid.skel_lockstep(T3b, proved): ifGrid.start prog fn L args m₁ ch ω₁ = .ok (g₁, c₁), withLabels.MemOk lab pay L c₁ g₁andprog.module.funcs.find? (·.name == fn.name) = some fn(the kernel is the module's function of its name;Grid.starttakes any function; seeGrid.FramesOkbelow), then for all contextsc₂withc₂ n = { c₁ n with oracle := (c₂ n).oracle },Grid.Lockstep L c₁ c₂ (fun x y => ReflTransGen (Grid.Step L c₁) g₁ x ∧ Grid.SkelRel lab pay x y).- T3 is
Grid.payload_runon T3b's relation (proved:Grid.skel_run). One run on(m₁, ω₁)to a grid that is done and not bad gives such a run on(m₂, ω₂), of as many steps and with an end related to the first's byGrid.SkelRel, and soundness there for every observation of the blocks whose value at its end satisfiesR. That value is T4's term.Grid.payload_runasksMem.BytesIn m₂.Knownof the second memory; it follows from the first's (Mem.SkelEq.bytesIn: related memories have onenext, blocks at the same numbers and the same pointer bytes).
Lemmas used (to prove unless marked proved)
Val.SkelandMemByte.Skelare reflexive and symmetric (equalities after erasure); so areMem.SkelEqandGrid.SkelRel(proved:Val.Skel.refl,Val.Skel.symm,Mem.SkelEq.refl,Mem.SkelEq.symm,Grid.SkelRel.refl,Grid.SkelRel.symm).Val.erasekeeps the constructor and the width of a word, and the length of a vector or aggregate. SoVal.Skelvalues have the same shape: a word and a word of one width, the same pointer, bothpoison, bothundef, or two vectors (two aggregates) of one length related element by element.-
Layout.decode_erase(proved): for every layout, data typet(Ty.data: integer widths are multiples of 8, no pointers, at any depth) and listbsof at mostl.stored tbytes,(l.decode t bs).map Val.erase = (l.decode t (bs.map MemByte.erase)).map Val.erase. So byte lists related pointwise byMemByte.Skeldecode toVal.Skelvalues, or both tonone. Both premises are needed (decode_twins):- an
i1reads one byte, and[byte 2]givespoisonwhere its erasure[byte 0]gives a word; - an
i8read from two bytes givespoisonfrom[byte 1, byte 1]and a word from[byte 0, byte 0].
A
loadreads exactlyl.stored tbytes, anddecodepasses each element and field a slice of at most its stored size, so the premises hold all the way down (Layout.decodeAll_erase,Layout.decodeFields_erase). ForscalarOf(Layout.scalarOf_erase): erasure keeps the bytes that are not data, so the list has apoison(anundef) byte exactly when its erasure has one, and otherwise both are all data. Then the number is below2 ^ (8 * length), which is at most2 ^ w, so both give a word.ptrOfreads its data bytes (all zero gives null), so a pointer load must be skeleton and outsidepay, which is (O3) andMemOk. - an
-
Layout.encode_erase(proved): for every layout, type and value,(l.encode t v).map (·.map MemByte.erase) = (l.encode t v.erase).map (·.map MemByte.erase). SoVal.Skelvalues encode to pointwiseMemByte.Skelbytes, or both tonone.encodewrites a word as data bytes, a pointer,poisonandundefas bytes that do not depend on any word, and pads withundef; the lengths depend only on the type and the shape (Layout.encodeAll_erase,Layout.encodeFields_erase). Mem.check_skel(proved): the checks of an access (Mem.check) read only the block's fields butbytes, so onMem.SkelEqmemories they give one fault, or related blocks at one offset (Except.Rel: one fault, or related results).ptrtointreads the block'saddrandgaddr, which agree too, so a cast of equal operands gives one result (inevalV_skel, byevalV_shape).Mem.load_skel(proved): one fault, or values that areVal.Skel, and equal outsidepay; a load from a block inpayis at a data type. Instance and twinload_skel(ani1load from a payload block gives a word in one run andpoisonin the other).Mem.store_skel(proved): a store ofVal.Skelvalues, equal outsidepay, gives one fault orMem.SkelEqmemories. Instance and twinstore_skel(different words stored to a block outsidepaygive memories that are not related).Mem.set_skel,Mem.log_skel,Mem.alloc_skel(one block number too) andMem.setLive_skel(proved; instancealloc_skel): setting related blocks at one number, recording one event, an allocation of one block and setting a block live or dead keepMem.SkelEq.Mem.freshis equal on equalnextby definition.evalV_skel(proved, for every scope, type, operand and two oracles; instance and twineval_skel): withMem.SkelEqmemories, and registers equal outside a setp, an operand that mentions no register ofp(Value.mentions p;evalV_regs) has one value, whatever the oracle numbers of the two scopes. An operand reads no oracle number: a cast in a constant expression is one LangRef admits there (CastOp.const:trunc,ptrtoint,inttoptr,bitcast,addrspacecast), none of which reads one (castV_ch: no cast butfpextandfptruncdoes), and the parser andevalVrefuse the others (twinfpext_twin: thefpextinstruction of ahalfNaN gives two words under two oracle numbers). So a skeleton operand has equal values. A constant expression reads only block fields butbytes(ptrtointof a global reads its address). A payload operand that is a register hasVal.Skelvalues byLabels.Rel; one that mentions no register has one value byevalV_skel. (O3) admits no other payload operand (TValue.payOk).Op.total_skel, one lemma per row ofOp.Total:Val.Skeloperands of a data type giveVal.Skelresults, or both fault, for every two oracle numbers. This is where the oracle may differ. Proved so far:lanes_skel(for all lane functions that give related results on related lanes, two oracle numbers allowed,lanesgives related results; byExcept.Rel.mapM) and the row oftrunc,zextandsexton scalars,intCast_skel(instance and twintrunc_skel: a lane function that makespoisonof the word 1 gives results that are not related),lanes2_skel(the same forlanes2and two-operand lane functions, also with second operands equal when a propositionPholds; instance and twinpair_skel), and the row of the integer binary operators on scalars,intBin_skel: for every width, and every operator and flags ofOp.Total(BinOp.total: no flag, notsdivorsrem), related scalars whose second ones are equal if the operator reads its value (BinOp.skelB: the shifts,udivandurem) give related results (instance and twinsbin_skel:or disjointof 1 and 2 gives 3 and of 1 and 1poison;sdivof -128 and of 0 by -1 faults and gives 0;shlof 1 by 1 and by 9 ini8gives 2 andpoison). Inexec, thebinrow islanes2_skelwithP := op.skelB = trueandintBin_skel. Theicmprow,icmpV_skel, holds for every layout, predicate and type, pointers included, on memories related for some set of payload blocks (related pointers are equal and have one address,Mem.addr_shape; instance and twinsicmp_skel: a pointer comparison faults on a memory with no block 1 and not onmemX 1;icmp eqof ani8with ani16faults). The rows offadd,fsub,fmulandfdiv(floatBin_skel, on scalars;fremfaults on both sides),fcmp(fcmpV_skel) andfneg(fnegV_skel) hold for every float type, operator or predicate, factors and two oracle numbers, with flags withoutnnanandninf, as (O3) requires (FastMath.checkrefusesnsz,arcp,afnandreassocon both sides; instance and twinsfloat_skel:faddof a NaN under two oracle numbers gives two NaN words; withnnana NaN operand, and withninfan infinite one, givespoisonand 0 a word). Inexec, thefbinrow islanes2_skelwithP := FalseandfloatBin_skel.floatBindelivers a word of the format for every oracle number (exists_deliver, Float.lean). Theselectrow,selectV_skel, holds for every type and condition (the condition is skeleton by (O1); twinselect_skel:trueandfalseselect a pointer to block 1 and one to block 2); theextractelement,insertelementandshufflevectorrows (extractE_skel,insertE_skel,shuffleV_skel) for every type and index or mask, and theextractvalueandinsertvaluerows (extractV_skel,insertV_skel) for every list of indices: related vectors and aggregates have one shape, so the operations take one path and fault together (twinselem_skel,shuffle_skel,value_skel: two indices, masks or index lists give results that are not related). The cast rows,castV_skel, hold for every layout, cast, two types, any oracle numbers and memories related for some set of payload blocks, sotrunc,zext,sext,fpext,fptrunc(floatCast_skel),sitofp,uitofp(intToFloat_skel) andbitcastbetween all types (bitcast_skel: related values have their poison bits at the same places,toBitList_skel,ofBitList_skel), and alsoptrtointandaddrspacecast(twincast_skel:ptrtointfaults on a memory with no block 1 and not onmemX 1). Themaxnumandminnumrow,fminmax_skel, holds for every type, two contexts and two scopes, with flags withoutnnanandninf, as (O3) requires: the intrinsic call (Thread.lean) gives one fault, or two results with related values that leave the scopes' memories unchanged. It islanes2_skelwithP := Falseandfloats2_skel(also the core offcmpV_skel), sincewithFlagsthen gives the IEEE 754 result (withFlags_some) and two floats of one type give related words (Val.ofFloat_skel); twinsmaxnum_skel: withnnana NaN operand, and withninfan infinite one, givespoisonand 0 a word. Thersqrt.approxrow,rsqrt_skel, holds for every two contexts, two scopes and related operands, with flags withoutnnanandninf: two 32-bit words give two floats, whatever the words and the two oracle numbers (by the definitions ofwithFlagsandFastMath.poisons),poisongivespoison, and every other operand faults on both sides. Its proof is by cases on the two operands and the definition ofintrinsic, and needs no theorem aboutrsqrt, sincersqrtreturns a word on every operand by definition; soGrid.skel_six's proof closure still has no theorem of FloatLib, Sem/Float or Sem/FloatRel. Inexec_call_skelits case is themaxnumcase with one argument (intrinsic_rsqrt: it never returnsnone). Instance and twinsapprox_skel: 1 under the oracle number 0 (its word+0misses the contract, so the fallback 1) and 4 under the word of 0.5 give the related words of 1 and 0.5; withnnan, -1 givespoisonand 1 a word; withninf, likewise+0.Labels.Ok's row and its twins:rsqrt_ok(MojoProofTest/Labels.lean).withAttrs_skel, proved for every layout, type, list of attributes and memories related for some set of payload blocks: on related values with norangeattribute, or on equal values,withAttrsgives one fault or related values.noundefneeds no premise: related values are both defined or both not (Val.Skel.defined, byVal.defined_erase), so it faults on both sides or neither;nonnullandalignread the address of one pointer (Mem.addr_shape); the attributes act in turn (Except.Rel.foldlM). Twinattrs_skel:range i8 0, 2gives a word on the word 1 andpoisonon the word 2. Inenterandexecthe premise comes from (O4) at payload parameters and results (norangethere) and from equal skeleton values elsewhere.enter_skel(phis byevalV_skelandevalV_pay),exec_skelandstep_skel. Each isExcept-agreement: both fault, or both succeed with related results andMem.SkelEqmemories. The cases followexecandstep:- skeleton statements: the operands are equal, so the results are equal (O2);
- payload statements: (O3) with
Op.total_skel; loadandstore: (O1) makes the pointer equal, andMemOkwithMem.load_skelandMem.store_skelgives the values;alloca: the count is equal (O1), the number isMem.freshon equalnext, and the addresses arec.addron equalch, so the new block is the same block of undefined bytes;atomicrmw:rmwon data words gives a data word, and the result is unset (S2);- calls: (O4);
- terminators: the condition is equal (O1), so the edge is the same.
step_skel(proved), as stated: for every labellinglab, payload blockspay, contextcwhose program passesLabels.Ok, oracleo, threads related byThread.Skelwhose first has frames that meetLabels.FramesOk lab c.prog, memories related byMem.SkelEq, withLabels.MemAtat the first thread's next statement (in its scope,Labels.MemNext),stepundercand under{ c with oracle := o }gives one fault or results related byStep.Skel lab pay (t₁.payRes lab):nextwith threads related byThread.Skeland memories byMem.SkelEq;waitat one intrinsic declared by one function, with arguments equal afterIntrinsic.eraseArgswhen the call's result is payload and equal when not (asStatus.Skelneeds);donewith memories related.Labels.FramesOk lab prog fsis the invariant this needs on the thread's frames: every frame's function is the module's function of its name (Array.find?), so it passesLabels.funcOkbyLabels.Ok(Labels.FramesOk.funcOk), and each two adjacent framesf(the callee) andg(its caller) meetlab.ret f.fn.name → f.dest.any (lab.reg g.fn.name)(List.IsChain): a function with a payload result returns into a payload register.Labels.Okalone does not give it: the kernel ofGrid.startis any function andf.destis the caller's register. Asking for the module's function, not only one that passesLabels.funcOk, is whatGrid.fire_skelneeds too: two threads at oneThread.at(which compares names) then run one function. The proof followsstep:- no frame, or no current block: frames related by
Frame.Skelhave one function, label and statement index, so both runs fault the same way; - a statement
st:exec_skel, withLabels.stmtOkfrom the frame function'sLabels.funcOk. Its labelst.res.any (lab.reg f.fn.name)ist₁.payRes lab. Anextreplaces the first frame and keeps the others; awaitis related asEff.Skelrelates it; a call ofgwith arguments related at its payload parameters readsg.blocks[0]?,g.checkand the functions of the frames (thenorecursecheck), all equal, and gives callee frames whose registerris the argument at the first parameter namedr, payload exactly whenris a payload register ofg, so they are related (List.find?ong.params.zip args); br,condBr,switch: the condition is skeleton (Labels.funcOk), so it has one value (evalV_skel), one edge or one fault, andenter_skel;unreachablefaults in both;ret: a skeleton operand has one value (evalV_skel) andwithAttrson one value and memories of one shape gives one result (withAttrs_shape); a payload operand is in a function with a payload result and is a register (Labels.funcOk), so its values are related (evalV_pay), and the result has norangeattribute, sowithAttrs_skelkeeps them related. The frames have one list ofallocas, set dead in turn (Mem.setLive_skel). With no caller both aredone. Otherwise the caller's registerf.destis set to values related byLabels.Rel (lab.ret f.fn.name), and byLabels.FramesOkit is a payload register when that label is true (Labels.Rel.mono,Frame.Skel.next).
- no frame, or no current block: frames related by
step_framesOk(proved):Labels.FramesOkholds after a step tonextof a context whose program passesLabels.Ok.execandenterkeep a frame's function anddest(exec_fn,enter_fn); a call's function is the module'sfind?of the callee's name (exec_call), and the callee'sdestis the call's result register, which (O2) makes payload when the callee's result is (Labels.stmtOk); aretdrops the first frame, and setting the caller's register keeps its function anddest.Grid.advance_skel(proved), as stated: for every labelling, payload blocks, contextsc₁andc₂withc₂ n = { c₁ n with oracle := (c₂ n).oracle }, grids related byGrid.SkelReland thread numbern, ifc₁ n's program passesLabels.Ok, threadnofg₁, if it runs, has frames that meetLabels.FramesOk, andg₁meetsLabels.MemAll, theng₁.advance c₁ nandg₂.advance c₂ nagree (Grid.Agree). Related statuses have one constructor, so both threads run or neither does; if both run,step_skel, and each result sets statusnof related arrays to related statuses (Option.Rel.set!):nextto running threads related byThread.Skelwith the memories after;waitto the threads before the step (related) at one intrinsic and declaration with the arguments asStep.Skelrelates them, which isStatus.Skel's wait case, with the memories before;doneto two returned threads with the memories after.Grid.FramesOk lab prog g(proved), the invariantGrid.advance_skelandGrid.fire_skelneed of the first grid: every running and waiting thread has frames that meetLabels.FramesOkunderprog(Status.FramesOk), the program of every context (hp : ∀ n, (c n).prog = prog, whichGrid.startgives,Grid.start_ctx), so every frame's function is the module'sfind?of its name. For every labelling and contexts whose programs areprogand passLabels.Ok, a grid step keeps it (Grid.advance_framesOk:step_framesOkfornext, a wait keeps the thread, anddonehas no frames), and so does a fire (Grid.fire_framesOk: a resume replaces the first frame by one of the same function anddest,Thread.resume_framesOkbyLabels.FramesOk.head), so every grid reachable from one that meets it does (Grid.reach_framesOk, byGrid.reach_inv). It holds at the start if the kernel is the module'sfind?of its name, as every thread has one frame of the kernel (Grid.start_framesOk, byGrid.start_run), and so at every grid reachable from the start if the program passesLabels.Ok(Grid.start_reach_framesOk; instancestart_framesOk, twinstart_framesOk_twin: a kernel with the name of the module's kernel and other statements). So two threads at oneThread.at(which compares function names) are at one statement of one function, and their next results are both payload or both not. Without the start's condition this fails:steprefuses a call to a function already on the stack only if it isnorecurse, so a kernel outside the module can call a module function with its name.Grid.fire_skel(proved, MojoProof/Sem/SkelStep.lean; instancefire_inst, on the launches of one kernel for every address choice and every two oracles, twinsfire_atCalls_twin,fire_prog_twin,fire_ok_twinandfire_framesOk_twinin MojoProofTest/SkelStep.lean), for every labelling, payload blocks, launch, programprogthat passesLabels.Ok, contexts as inGrid.advance_skelwhose programs are allprog, grids related byGrid.SkelRelwhose first meetsGrid.FramesOk lab progandGrid.AtCalls c₁, and thread numbern:g₁.fire L c₁ nandg₂.fire L c₂ nagree.Grid.AtCalls(W5, kept by every step, fire and path and given byGrid.start) says each waiting thread is at a call of the saved declaration, the module's bodiless function of the callee's name, whose intrinsic is the saved one (Thread.AtCall); without it a waiting status could hold any declaration, andresumeAllapplies its attributes. The one program makes the lanes' frames meetLabels.FramesOkunder one module. Statuses have one constructor, so threadnwaits in both or in neither; if it waits, the intrinsic and declaration are one, and the arguments are equal or (payload result) equal afterIntrinsic.eraseArgs, which changes only a shuffle's exchanged value (Intrinsic.barrier_args,Intrinsic.shfl_args). The layout is one (c₂differs in the oracle only).- barrier
[x]:eraseArgsis the identity, soxis one, and so are the checks on it. The group depends onnandLonly. At each member, related statuses have one constructor, and related waiting threads have one intrinsic, one argument list (a barrier) and oneThread.at(Frame.Skelkeeps function, label and index), sostatesis one list or both fault.resumeAllwith no results resumes related threads to related threads (Thread.resumewithnonesets no register), andMem.log_skelrelates the memories. - shuffle
[msk, a, b, c]:msk,bandcare one at each lane, so the checks,lanes, and thepartsbut their exchanged values are one, andparts.mapM idisnoneon both sides or on neither (List.Forall₂.mapM_id). Every lane is at threadn'sThread.at(Thread.Skel.at), so byGrid.FramesOkunder one program all run one function at one statement and have oneThread.payRes, threadn's (Thread.payRes_at). If it is false the exchanged values are equal, so eachres kis one value; if true they are related byVal.Skel,srckeeps that (List.find?on one index list, the defaultpoisonon both sides), and so doesres k.resumeAllthen sets each lane's result register towithAttrsof related values: equal values give one result (withAttrs_shape), and related values with norangeattribute related results (withAttrs_skel; both inwithAttrs_rel). With a payload result the saved declaration has norangeattribute: byGrid.AtCallsit is the module's declaration of the lane's current call, which passes (O3) as a statement of a function of the module (Thread.AtCall.noRange; twinsshfl_range_twin,fire_atCalls_twin,fire_ok_twin). The resumed threads are related (Frame.Skel.nextat the call's result register, payload exactly whenThread.payResis true), and the memory is unchanged. ldmatrix,mmaand ill-typed arguments: both fault.resumeAllis aList.foldlMover one list of thread numbers, soExcept.Rel.foldlMwithOption.Rel.set!at each step gives related arrays (resumeAll_skel,Thread.Skel.resume). Another matching of the threads of a collective call would change the matching but not the argument: it reads positions, step counts andThread.at, all equal in related grids.
- barrier
Thread.pending_skel(proved, MojoProof/Sem/SkelStep.lean; instancepending_inst, twinpending_twinin MojoProofTest/SkelStep.lean), for every labelling, payload blocks, context whose program passesLabels.Ok, oracle, threads related byThread.Skelwhose first's frames meetLabels.FramesOk, and memories related byMem.SkelEq: the pending accesses (Thread.pending) under the context and under it with the oracle are equal. Related frames have one function, label and statement index, so both threads are at one statement or neither. Its function passesLabels.funcOk(Labels.FramesOk.funcOk), so the statement passesLabels.stmtOk, whose (O1) makes the pointer operand of aload,storeoratomicrmwskeleton; it evaluates to one value (evalV_skel). The access's thread, length and flags read only the context'swhoand layout, which the oracle does not change, and the statement. WithMem.SkelEq.tracethis givesrace. Its twin is a store through a constantgetelementptrwhose index is a payload register, which fails (O1): the two threads' accesses are at different offsets. The twin is an AST form only, not LLVM IR: a constant holds no register, and the parser refuses its text.
Proof
Grid.start_skel (proved): the start's steps read the caller's memory in two places.
Mem.checkClosed reads next, which blocks exist, their sizes and pointer bytes, and those are
equal by Mem.SkelEq (Mem.checkClosed_skel). launchArgs checks each pointer argument's
nonnull and align attributes with withAttrs, which reads only the memory's shape (which
blocks exist, their spaces, sizes and addresses); Mem.SkelEq keeps the shape
(Mem.SkelEq.sameShape), so withAttrs gives one result on both memories (withAttrs_shape).
The other steps are shared and launchArgs' allocations, which allocate from ch, encode the
arguments and number blocks from next; those are equal on both sides (Mem.allocNext_skel,
shared_skel, launchArgs_skel). Its contexts differ only in oracle.
Grid.skel_lockstep (proved), by fields (with Grid.FramesOk at every reachable grid of the
first run, from the start's, by the premise on the kernel, and Grid.AtCalls there, by
Grid.start_reach_atCalls; every context's program is prog, Grid.start_ctx):
advance:Grid.advance_skel, withMemOkat the first grid, which is reachable, andGrid.FramesOkthere. A step's target is reachable, soSis kept (Grid.Agree.imp).fire:Grid.fire_skel.done: statuses have one constructor (Grid.SkelRel.done).trace: byMem.SkelEq.trace.race: byThread.pending_skelandtrace.
MemOk is needed on the first run only. The addresses it speaks of are skeleton values, equal in
both runs, so the conditions hold at the second grid of each related pair.
Obliviousness on terms (MojoProof/Sym/Payload.lean)
The checks above on a block summary's node table
(Summary, MojoProof/Sym/Checker.lean), for every labelling, function and summary; they are
Bools the kernel evaluates.
- Roles (
roles lab fn ns): nodej's role isSNode.payon the roles of nodes0..j-1(roles_getElem?). An entry register is payload by its label, a constant never, a node by its role (SVal.pay). A node is payload if an operand is (aselect's condition among them); acall,getelementptr(with one index, orSNode.gepNwith another number) orloadalso if its statement's result register (resReg) is labelled payload (payload enters through loads); a float operation always ((O2): its NaN results read the oracle); aloadafter astore(SNode.loadAfter) always; a constant's node (SNode.constAt) never, and a global's pointer (SNode.globalAt) never, since the theorems below take the two valuations with one table of globals (hg). So agetelementptr,loadorstoreon a global can be oblivious underSummary.obliviousbelow (layernorm's%448,ln_store_oblivious, MojoProofTest/SymSeg.lean). Nodes of the other kinds carry no statement position, so their labels are not read: their roles come from their operands. Summary.obliviousis (O1) on terms: the exit condition, each effect's pointer, the operands of eachgetelementptrandloadnode, the condition of eachselectnode and the index of eachextractelementandinsertelementnode are payload-free.Summary.agrees: every register the summary sets whose entry is payload is labelled payload. It is an implication and not an equality: a register labelled payload may hold a skeleton value, asLabels.Okallows. What T3c needs at the next block's entry is that a skeleton label means a skeleton value.Summary.phiAgreesandSummary.agreesI. An edge into a block withphis also sets the target'sphiresults (enter,Valuation.into). These are in no summary'sregs: the target's summary starts after them, and reads aphiresult as an entry register, by its label. Soagreesalone does not give the property at the next block's entry: a payload value can flow through aphiinto a register labelled skeleton, and from there into a branch, with both blocks' checks passing (phiFn,phi_payload_branch).phiAgrees lab fn lbl S dchecks eachphiat the head of blockd(phisAt, the listenterreads). If its operand forlblmentions a register whose entry at the block's end is payload (Summary.endPay), the operand must be a register and its result register must be labelled payload (stated below).agreesI lab fn lbl Sisagreestogether withphiAgreesat each target ofS's exit. The property at the next block's entry rests onagreesI, by cases on a registerr:ris set by aphiof the edge:phiAgreescovers it, andentersets it last;- otherwise,
ris set by the block:agreescovers it; - otherwise,
rkeeps its value from the block's entry, whose label is the same register's label, so the property comes from the block before, by induction along the path.Labels.OkrefusesphiFnas well: thephihas a skeleton result and a payload operand, (O2) (phi_payload_labels).agreesIis the check on the summaries, whichLabels.Okdoes not read.
rolesis the foldscanSnoc(MojoProof/Sym/Term.lean) atSNode.pay, and its lemmas arescanSnoc's (scanSnoc_length,scanSnoc_snoc,scanSnoc_getElem?, for every function and list).valsis the same fold atSNode.eval, written out, andvals_fold,vals_length,vals_snoc,vals_appendandvals_getElem?are these lemmas there.
Instances (MojoProofTest/Payload.lean, one program): under vaddLab ["25", "27", "28"], the roles
of vector_addition's block %21 are its two loads and the fadd (vadd21_roles), and the
summaries of its four blocks are oblivious and agree (vadd_oblivious). Twins (vadd_twins):
with the gep %24 payload, %21 agrees but is not oblivious (a load through a payload pointer);
with %28 skeleton, or nothing payload, it does not agree.
The phi edges. The first is the naive matmul kernel's edge %51 → %67
(MojoProofTest/SymPhi.lean), into %68 = phi float [%48, %51]:
- with
%48and%68payload,agreesIaccepts it (phi_agrees); - with
%68skeleton,agreesandobliviouspass on both blocks andagreesIrefuses the edge (phi_twin).
The second is a load fed to a phi whose result decides a branch, written as an AST (phiFn):
- with
%ppayload,agreesIrefuses the edge andLabels.Okrefuses the program; - with
%qpayload too, the edge agrees, and the branch block is not oblivious (phi_payload_branch).
Two runs (for every labelling lab, payload blocks
pay, table and pair of valuations).
Valuation.Skel lab pay V₁ V₂: one program, environment, thread and function, memories related byMem.SkelEq pay, and equal registers wherelablabels skeleton. The step counts, thefmul contractoperands, the globals, the address choices and the oracles are free. The theorems below take one table of globals besides (hg : V₁.ctx.globals = V₂.ctx.globals), which a global's pointer reads; no other skeleton node reads them (a float operation is payload, andgetelementptrandcallread only the program, the environment and the memory's shape).Valuation.Relbelow has one table of globals, so it meets them.Valuation.LoadsOk lab pay V ns: underV, the pointer of eachloadnode whose statement's result register is skeleton points outsidepay,Labels.MemAtat aloadon terms. When everyloadnode has a payload result register it holds for everypay(Valuation.loadsOk_of_pay;vector_addition's case).vals_skel: under valuations related byValuation.Skelwith one table of globals meetingLoadsOkunder the first, every node whose role is skeleton has one value under both: the same fault or the same value. Proof: induction on the table byvals_snocandroles_snoc. A skeleton node's operands are skeleton (SNode.pay), so they have one value (SVal.eval_skel: a skeleton register byValuation.Skel.regs, a node by induction).bin,castandextractare functions of their operands.icmp,getelementptrandcallread the memory only through its shape (icmpV_shape,gep_shape,withAttrs_shape, withMem.SkelEq.sameShapeandVal.namesIn_top). Aloadreads one pointer, outsidepaybyLoadsOk, soMem.load_skelgives one value. A global's pointer is the table's. A float operation is never skeleton.Summary.oblivious_skel: an oblivious summary, under such valuations, exits to one block (or to none) under both, and each effect has a pointer (SEff.ptr, none for analloca, so an oblivious summary has none), with one value under both: its exit condition and pointers are payload-free, sovals_skelapplies. The exit isExit.dest, so this covers a branch into blocks withphis (Exit.phi, whose conditionobliviousreads), and not onlyExit.target's branches. Whichphiassignments the edge makes, and whether they are skeleton where the labels say so, is the next block's entry relation (agreesI), below.
Instances (one program each, every pair of related valuations of its function and every pay):
nodes 0, 1, 2, 4 and 7 of vector_addition's %21 (the truncation, extension and three geps)
have one value (vadd21_skel), and, when the entry block's three loads of the byval arguments
read outside pay (a premise), each of the four blocks exits to one block and accesses one
address per effect (vadd_skel); the naive matmul kernel's %51, a phi exit into %67, and
%67's store, under phi_agrees's labelling (naive_skel).
To the next block's entry (T3c on terms, MojoProof/Sym/Payload.lean)
For every labelling lab, payload blocks pay, summary S of
block l of a function, and pair of valuations.
Definitions.
Valuation.Rel lab pay V₁ V₂:Frame.SkelandMem.SkelEqon valuations. One program, environment, thread, globals and function; memories related byMem.SkelEq pay; at every register, no value in both or values related byLabels.Relat its label (equal where skeleton,Val.Skelwhere payload), and the same for thefmul contractoperands. The step counts, the address choices and the oracles are free. It givesValuation.Skel(Valuation.Rel.skel).- (O3) on terms,
SNode.payOk lab fn ps nd: a payload node's operation gives related results on related operands, asOp.Totalabove requires:- an integer
binhas no flag and is notsdivorsrem(BinOp.total), and its second operand is skeleton when it is a shift amount or a divisor (BinOp.skelB); - a float operation has neither
nnannorninf; - a
getelementptr, with any number of indices, has skeleton operands (only its result label is payload); - a
loadhas a skeleton pointer and loads a data type (Ty.data, read byloadDataat the statement), so the bytes of a payload block decode to related values (Mem.load_skel); - a
selecthas a skeleton condition (selectV_skelrelates the results of one condition;obliviousrequires it too), and anextractelementand aninsertelementa skeleton index (extractE_skel,insertE_skel); icmp, the integer casts,extractvalue,insertvalue(insertV_skel),call, the integer maxima and minima (intMinMax_skel) always (a global's pointer and a constant's node are never payload);- a
loadafter astore(SNode.loadAfter) has a skeleton pointer, each effect it carries has a pointer and it is skeleton (SEff.ptr), and it loads a data type. Its memory is the one its effects make from the entry memory.SNode.eval_relruns those effects in the two runs with every block payload (SEff.run_relatfun _ => True, from the entry memories' relation withBlock.SkelEq'ssamedropped), so the two memories have equal shapes and payload-related bytes whatever the stores write, and the two loads giveVal.Skel-related values (Mem.load_skel). No premise on the stores is needed: the node's role is always payload. Layernorm's%453from statement 1 through 9 passes under the labelling whose one payload register is the triple loaded from the shared-memory global, and fails with the stack slot%12payload too (ln_after_rel, MojoProofTest/SymSeg.lean).Summary.payOk lab fn S: every node ofSwhose role is payload passes, on the roles of the nodes before it (a skeleton node is not checked:SNode.eval_skelcovers it).
- an integer
Valuation.StoresOk lab pay V S: underV, eachstoreeffect ofSwhose value operand is payload stores through a pointer into a block ofpay(Labels.MemAtat astore, on terms).Summary.endPay lab fn S r: registerr's entry at the block's end (SState.get: its node, or the entry registerr) is payload.Summary.phiAgrees: on the edge fromlintod, eachphiat the head ofdwhose operandvforlmentions a register with a payload entry at the block's end (endPay, itself or inside a constant expression) is a register%r, and its result is labelled payload. An operand that mentions none (a constant, a global, a register with a skeleton entry) passes whatever the result's label: it has one value in both runs. Counting every operand that is not a register or an integer as payload instead would refuse a float constant into a skeleton result and accept a constant expression on a payload register into a payload result, whose values in two runs need not be related (agetelementptron a payload index gives two pointers).
Statements.
vals_rel: under valuations related byValuation.Rel, meetingLoadsOkunder the first, on a table whose nodes passpayOk, every node's value is related at its role: one fault, or equal values where the role is skeleton and values related byVal.Skelwhere it is payload.SEff.run_rel: with values related as in (1), each effect's pointer with one value under both (Summary.oblivious_skel) andStoresOk, the effects give one fault or memories related byMem.SkelEq pay.Valuation.after_rel: fromoblivious,agrees,LoadsOk,payOkandStoresOk,(V₁.after S).Rel lab pay (V₂.after S).Valuation.into_rel: withagreesI lab V₁.fn l Sin place ofagrees,(V₁.into l S).Rel lab pay (V₂.into l S).
Proof.
- Induction on the table (
vals_snoc,roles_snoc), asvals_skel. A skeleton node:SNode.eval_skel(its operands are skeleton, so equal). A payload node: its operands are related at their roles (SVal.eval_rel: a register byValuation.Rel.regs, a node by induction, a constant equal), so byVal.Skel(Labels.Rel.to), and bypayOk:bin:lanes2_skelwithintBin_skel(the second operand is equal whenskelB);icmp:icmpV_skel; integer casts:lanes_skelwithintCast_skel;extractvalue:extractV_skel;- float operations:
lanes2_skelwithfloatBin_skel(any oracle numbers andfmul contractoperands); call,getelementptr: one value, as inSNode.eval_skel;load: one pointerq;Mem.load_skel(withTy.data) gives related values, soVal.Skel.definedgives onenoundefcheck. A fault is the same fault on both sides:Except.Relrelates.error eonly to.error e.
Except.Rel.foldlMfromValuation.Rel.mem. Each effect's pointer has one value, so one addressq. Aloadeffect records one event (Mem.log_skel). Astorewrites values related at the value operand's role: equal if skeleton; if payload, related byVal.Skel, andStoresOkputsqinpay; soMem.store_skelapplies.- Field by field. Context and function:
afterkeepsV's. Memory: (2), orV's memories when the effects fault in both. Registerr(regVal): if the block sets it, its entryxhas values related atx's role (1), andagreesgives a payload label when that role is payload (Labels.Rel.mono); if not,V's registers.fmul contractoperands (regProd): none for a register the block sets,V's otherwise. intoisafterexcept for an exit into blocks withphis (Exit.phi) whose condition selects a targetd, andoblivious_skelgives onedunder both. Thereenterruns from the framesValuation.frameAt, related byFrame.Skelby (3), and evaluates eachphi's operand forlin each run's scope (one layout and globals byValuation.Rel). An operand that mentions noendPayregister has one value (evalV_skel): a register with a skeleton entry at the block's end has one value there, by (1) if the block sets it and byValuation.Rel.regsif not. OtherwisephiAgreesgives a register with a payload result, and its values are related byVal.Skel(evalV_pay).Frame.Skel.setAllandFrame.Skel.gotogive related frames (enter_rel), so related registers and operands (enter_fields: the function is kept). A fault ofenteris one fault in both runs, andintois thenafter.
Lean (MojoProof/Sym/Payload.lean, for every labelling, payload blocks, summary and pair of
valuations): SVal.eval_rel, SNode.eval_rel, vals_rel, SEff.run_rel,
Valuation.after_regs, Valuation.after_rel, enter_rel and Valuation.into_rel, as above.
LoadsOk and StoresOk are premises: they are Labels.MemAt on terms, and discharging them from
Labels.Ok and the run's memory invariant is the composition's work.
Instances (MojoProofTest/Payload.lean, one program each, every pair of valuations related by
Valuation.Rel and every pay):
vadd21_into:vector_addition's block%21undervaddLab ["25", "27", "28"], givenStoresOk(its store of the sum%28writes topay), relates the valuations at the next block's entry;naive_into: the naive matmul kernel's%51underlabIn SymPhi.naive.fn_0 ["48", "68"]relates the valuations at%67's entry, after thephi%68(no store, soStoresOkholds).
Twins: vadd21_payOk (block %21 passes payOk; with its fadd marked nnan it does not) and
phi_operand_twin (phiFn with %p and %q payload agrees on its edge; with
the phi operand splat (i32 %p), a constant expression on a payload register, it does not).
Along a path, and two runs of a returning path (MojoProof/Sym/Payload.lean)
For every labelling lab, payload blocks pay, function fn and path (l, ds, S) :: ps (the
block checker's coversPathWith false and WalkWith false, whose blocks after the first are
entered through Valuation.into).
Definitions.
pathOk lab fn l S ps: every summary of the path is oblivious, agrees withlabon its exit's edges (agreesIat its own label) and passespayOk. ABoolon summaries only.Valuation.PathMem lab pay V l S ps:LoadsOkandStoresOkof each block at its entry valuation in the run fromV(Valuation.intoof the block before).Cond.effsIn S d: obligationdruns only effects of summaryS(aCond.mem eseach of whose effects is one ofS.effs;trueforCond.okandCond.bool). ABool. The obligationssummarizemakes pass it (their oneCond.memrunsS.effs);coverslets a path's lists hold more conditions thanS.obls, so it is checked, by the kernel, per path.
Statements.
Valuation.last_rel: ifV₁.Rel lab pay V₂,V₁.fn = fn,pathOkandV₁.PathMemhold, then the entry valuations of the last block (Valuation.lastWith false) are related, the last block's label and summary are one under both, and the valuations after the last block (Valuation.after) are related.Block.sound_ret_rel: for two contexts of one program and two threads of one frame each at blockl's positionp0, whose frames have one list ofallocas(premiseha), ifcoversPathWith falseaccepts the path,pathOkholds, each obligation of the path passesCond.effsInat its block's summary (premisehd), the first entry valuation meetsWalkWith false, the last block returns, the entry valuations are related and the first meetsPathMem, then both threads run the path and their next steps return (.done), and the two returned memories (the memories at the last block's end with each frame'sallocasmade dead) are related byMem.SkelEq pay.Cond.holds_rel: for valuations related byValuation.Reland a summarySthat is oblivious, passespayOkand meetsLoadsOkandStoresOkunder the first, every obligationdwithCond.effsIn S dthat holds under the first onS's node values holds under the second.WalkWith.rel: ifV₁.Rel lab pay V₂,V₁.fn = fn,pathOkholds, every obligation of the path passesCond.effsInat its block's summary, andV₁.PathMemholds, thenWalkWith falsefromV₁givesWalkWith falsefromV₂.
Proof.
- Induction on
ps. A one-block path:pathOkgivesoblivious,agreesI(soagrees, its first conjunct) andpayOkatfn = V₁.fn, andPathMemgivesLoadsOkandStoresOk, soValuation.after_rel. A longer path:Valuation.into_relrelates the next block's entry valuations, which keep the function (Valuation.into_k), and the induction hypothesis applies to the rest.lastWith false's label and summary are the path's last, so they do not depend on the valuation. Block.sound_retWithfor each thread (the second's program and function are the first's byValuation.Rel, and its last block is the first's by (1)): each run's steps reach the last block's end on the memorymethat its effects make from its entry valuation (SEff.run), and the next step returns. That memory isValuation.after's, so (1) relates the two. The return sets each block of the frame'sallocasdead in turn (List.foldlofMem.setLive b false); with one list in both frames (ha),Mem.foldl_setLive_skel(MojoProof/Sem/Skeleton.lean; induction on the list,Mem.setLive_skelat each block) relates the returned memories. The second run'sWalkWith falseis (4)'s.vals_relrelates the node values.Cond.ok x:SVal.eval_relrelatesx's results (Except.Rel: one fault or two values), so anokunder the first is anokunder the second.Cond.bool x: the two values are related byVal.Skelat least (Labels.Rel.to), which keeps a scalar's width (Val.Skel.scalar); a word under the first is a word under the second, aspoisonandundefare not defined (Val.Skel.defined).Cond.mem es: each effect is one ofS.effs(Cond.effsIn), whose pointers are one under both (Summary.oblivious_skel) and whose payload stores write topay(StoresOk), soSEff.run_relgives one fault or related memories.- Induction on the path. Each block's obligations by (3) at its entry valuations; each exit's
destination is one under both (
Summary.oblivious_skel's first conjunct); the next block's entry valuations are related byValuation.into_reland keep the function (Valuation.into_k).
Why hd: covers asks only that S.obls be a prefix of the block's list, so a path may carry
a Cond.mem of effects that are not the block's, whose pointers oblivious does not check.
Why ha: Valuation.entry does not read a frame's allocas, so Valuation.Rel, WalkWith false
and PathMem say nothing about them, and frames that differ only in allocas return different
memories. Twin (MojoProofTest/Payload.lean's allocas_twin, for every context, step count, frame,
labelling and pay): the frames with allocas [] and [1] have related entry valuations on a
memory whose block 1 is live, and the returned memories are not related (block 1 is live in one and
dead in the other).
Valuation.storesOk_of_skel: when no store effect has a payload value operand, StoresOk
holds under every valuation (as Valuation.loadsOk_of_pay for LoadsOk).
Loads and stores through registers (for every labelling, pay, valuation, table or summary and
list of registers rs):
SVal.baseIn ns rs p(aBool):pis a register ofrsor a node ofnsthat is agetelementptron one.SVal.eval_baseIn: if the values ofrsunderVname only blocks of a setB(Val.NamesIn) andSVal.baseIn ns rs p, a pointer value ofponns's node values points to a block ofB. Proof: a register's value is its own; agetelementptrkeeps its base's block (gep_namesIn, MojoProof/Sem/Schedule.lean).Valuation.loadsOk_of_regs: if the values ofrsname no block ofpayand eachloadnode with a skeleton result has its pointer's base inrs(on the nodes before it),LoadsOkholds.Valuation.storesOk_of_regs: if the values ofrsname only blocks ofpayand eachstoreeffect of a payload value has its pointer's base inrs,StoresOkholds. These dischargeLoadsOkandStoresOkfrom facts about the entry registers, which a caller gets from the launch's start facts; theBools are decided by the kernel.
Instance (MojoProofTest/Payload.lean, one program, every two contexts, threads and memories, and
every pay): vadd_runs, vector_addition's path %4 → %21 → %31 under
vaddLab ["25", "27", "28"], for frames with one list of allocas, the first thread's
WalkWith false and every p0, p1, p2, out and struct tail tl. Its premises are start
facts of the first run: the first frame's registers %0 to %2 point to offset 0 of p0 to p2,
outside pay, and the struct load %5 through %2 reads a struct whose first field points to
offset 0 of out, in pay (the start facts of Kernel.sound_map2, MojoProof/Sym/Kernel.lean, give
these with pay the one block out). From them, Valuation.loadsOk_of_regs (registers %0 to
%2) gives %4's LoadsOk and Valuation.storesOk_of_regs (register %6, which is out's
pointer at %21's entry by vadd4_reg6) gives %21's StoresOk; the second thread's
WalkWith false is WalkWith.rel's. The kernel decides the rest (coversPathWith false, pathOk,
Cond.effsIn, the pointer bases, loadsOk_of_pay for %21 and %31, storesOk_of_skel for %4
and %31). Twin: vadd_pathOk, where pathOk passes under that labelling and fails with %28
skeleton.
Not proved:
- the discharge of
LoadsOkandStoresOkfromLabels.MemOk(the grid-level memory conditions on statements): it needs, at eachloadandstorethatBlock.soundruns, the statement's pointer to be the term's, whichSState.run_sound(MojoProof/Sym/Block.lean) proves but does not state; - two runs of a grid (every thread and its interleaving,
Grid.SkelRel).
T3c: partial payload operations (after T4)
The partial operations are:
rsqrt.approxundernnanorninf(without them it is inOp.Total,rsqrt_skel). Its contractrsqrtOk(Float.lean) admits PTX's results for the special inputs: a NaN or negative operand gives a NaN, a zero or subnormal one gives an infinity of its sign,+∞gives+0.rsqrtreturns the oracle's word if it meets the contract and else its fallback, FloatLib'sModel.rSqrtof the operand with subnormals flushed, which meetsrsqrtOkon every binary32 operand (rsqrtOk_rSqrt), so every value meets it (rsqrtOk_of_rsqrt). Undernnanorninfwhether it givespoisondepends on the operand, and T3c takes the domain hypothesis;udivanduremby a payload divisor, andsdivandsremwith a payload operand;nsw,nuw,exactanddisjointon payload, and shifts by a payload amount;nnanandninfon payload float operations and calls;fptosiandfptouion payload;rangeon a payload parameter or result.
Each is to be admitted in (O3) if the block summary gives its operand terms, and if the hypothesis
Φ₁ ∧ Φ₂ says that the terms, evaluated on each run's payload and oracle, lie in the operation's
domain. Op.total_skel for such an operation then holds on the operands that occur. Φ is
proved once for every payload from bounds on the term (for example, that a payload divisor is
nonzero, or FloatLib's bounds on a float term). Not started: it needs T4's terms.
T4: the output term (with the block summaries)
T4 has no Lean statement. This section fixes its definitions, its statement and a proof route.
Definitions (an alloca's address is a skeleton choice, Ctx.addr; the oracle holds only float
freedoms):
Atom:arg i,sreg r d,laneidandaddr(skeleton);cell b i(the byteiof payload blockbat the start, or the word at offseti: which of the two is not fixed);orc n k i(threadn's payload choice at stepk, indexi).SVal: an atom, a constantVal, or an operation ofOp.Total(the partial ones are left out) applied toSVals at an oracle position.SVal.eval (env : Atom → Val) : SVal → Except Fault Valapplies the semantics' own operation functions (floatBin,lanes2,castV, ...), so the term is computed by the semantics and is not a model of it.Summary.out : Launch → List Val → Nat → Nat → SValgives the term of each output word.
Statement. Let Σ be a block summary (MojoProof/Sym) of prog's kernel fn, sound for L, args and ch.
For every caller memory m with Mem.SkelEq pay m₀ m and every oracle ω, every grid reachable
from the start on (m, ω) in which every thread has returned holds, at each output word, the
bytes of (Σ.out L args b i).eval (env m ω). Here env m ω reads cell atoms from m, orc
atoms from ω, and skeleton atoms from the launch.
Proof route. The invariant along a run is TermRel:
- every payload register equals the evaluation of its term in the block checker's symbolic state at the same instruction;
- every byte of a
payblock equals the byte of its term's evaluation.
The step: each step keeps TermRel with the symbolic step. It is not proved; it would extend
Block.sound (MojoProof/Sym/Block.lean). With it, the done grid of one run holds out's
evaluation, and schedule independence (Grid.start_sound, docs/proofs/schedule.md) gives every
done grid.
The term block %21 of vector_addition stores (3c; one program, MojoProofTest/Payload.lean)
This fixes, on the summary Kernels.vadd.b1 that mojo_kernel generates
(MojoProof/Kernels/Vadd.lean), the term of the value the block stores, and the step whose oracle
numbers its fadd reads. It is a check on one summary, not T4.
Definition. cellOk ra rb ro s S (a Bool function in the test) holds when:
S's effects are[load _ _ (node pa), load _ _ (node pb), store _ _ (node j) (node po)];- node
jisfbin fadd fm float s (node a) (node b)for some flagsfm; - nodes
aandbare loads throughnode paandnode pb; - nodes
pa,pbandpoaregeps on the entry registersra,rbandroat one indexi(the second operand of the store'sgep).
Statement. cellOk (local? "10") (local? "8") (local? "6") 6 Kernels.vadd.b1 = true. The block stores,
through the gep of the output %6 at an index i, the fadd at step 6 after the block entry of
the loads through the geps of the inputs %10 (a) and %8 (b) at the same i. So, by
SNode.eval, under every valuation V the stored value is lanes2 of floatBin float fadd fm on
the two loaded values, with oracle number Nat.pair (V.k + 6) 0 for its one lane.
Proof. decide +kernel on the summary.
Twins. The check fails:
- with the inputs swapped (
%8read first); - with the output register replaced by
%10; - at step 5;
- on the entry block's summary
Kernels.vadd.b0, which has no store.
The value statement (vadd21_store, vadd21_store_sound). SumStored V me (a Prop in
the test) says, for a valuation V and a memory me, that:
- register
%19holdsr, and thesextto 64 bits of thetruncto 32 ofrisi(%23); %10,%8and%6holdpa,pbandpo, and thegetelementptr inbounds floatof each at indexiis a pointer:qa,qbandqo;- the float loads (address space 0, alignment 4) from
V's memory atqaandqbgivexaandxb, cellsiof the inputs; lanes2offloatBin float fadd {contract}with oracle numberNat.pair (V.k + 6) jfor lanejgivesxonxaandxb;meis the store ofxatqoonV's memory with the two loads' trace entries (soqoholds the bytes ofx), and whenxis a float, the float load atqofrommegivesx.
For every valuation of vector_addition's function in a context of its program, every memory
that Kernels.vadd.b1's effects make from it satisfies SumStored (vadd21_store). With vadd21_sound
(Block.sound): for every context of the program and thread whose innermost frame is at %21's
entry and whose obligations hold, the steps reach the block's end with such a memory, at the
entry valuation (vadd21_store_sound).
Proof. The summary's table and effects, and the six statements they name, are the program's
by rfl; SEff.run, vals and SNode.eval unfold, and each bind that succeeds gives a value
(Except.bind_eq_ok). The load back is Mem.load_store_codec with Layout.Codec.float.
Instance and twin (vadd21_store_twin). The premises hold on MojoProofTest/SymRun.lean's run
at index 2 (vadd21_hds). For every valuation V, SumStored V V.mem fails: the memory the
block makes has three more trace entries.
Not proved.
- Whether
xis a float: it is unless an input cell is poison (an undefined cell faults). - T4 for every program.
T5: relations on payload, for every relation
Let R : Val → Val → Prop, and let C couple two oracles: for example, equal choices, or any
choices for an operation whose result R relates for every choice. Let o.Respects R C say:
R-related argument lists give R-related results, or both fault, under C-coupled oracle
numbers.
Statement (SVal.eval_respects, not stated in Lean; SVal.eval_rel is T3c's Lean theorem on
the skeleton relation, another statement). For every term t whose operations all
respect R under C, every two environments with R (env₁ a) (env₂ a) for every atom a of
t, every two oracles coupled by C, and R v v for every constant v of t: t.eval env₁
and t.eval env₂ both fault or give R-related values.
The premises are on the atoms and constants of t, not on reflexivity of R, because R is
arbitrary: for R x y := x ≠ y and a constant term, the two evaluations
are one value, which R does not relate. A skeleton atom has one value in both runs, so its
premise is R v v at that value; for the relations of the rows below this holds on defined
values.
Proof. Induction on t:
- an atom or a constant: by the premise;
- an operation: the induction hypothesis on the arguments gives
List.Forall₂ R, andRespectsfinishes. Faults propagate on both sides.
The instances are one lemma per row, one relation each: FinEq, NaN equivalence, the error
relation with its validity flag, and the rsqrt relation. These are float results about the
semantics' operations; results about floats alone belong in FloatLib. Not every row is a Respects lemma on its
relation: the coupled maxnum / minnum row (maxnum_nanEq, fminmax_nanEq,
fminmax_vec_nanEq) relates identical operands under two oracle numbers of one parity, so its
input relation is equality, and it does not compose with NaNEq on the operands. No parity
coupling can make it: with
q = 0x7fc00000 (a quiet NaN), s = 0x7fa00000 (a signaling NaN), NaNEq q s, second operand
1 and n = n' = 1, maxnum true q 1 1 = 1 and maxnum true s 1 1 is a NaN, which are not
NaNEq (mx 1 and maxnum_inst in MojoProofTest/FloatRel.lean; LangRef's quiet and signaling
NaN rules for llvm.maxnum). A term with a maxnum node that a NaN can reach therefore gets
NaNEq at that node only when its operands are equal words in both runs, which SVal.eval_respects
must take as the node's premise.
T5's rows, one operation at a time (MojoProof/Sem/FloatRel.lean)
These are the rows that are proved, for one operation each (on scalars or on words), not for
terms: SVal.eval_respects is not stated here.
Definitions.
FinEq x yonModel fmt:x = y, or neither is finite (GPUProof.UpToNaNat the words that are not finite, GPUProof/NaN.lean).NaNEq x y:x = y, or both are NaNs (GPUProof.UpToNaN Model.isNaN, GPUProof/NaN.lean).Estwith fieldsvalue : ℝ,bound : ℝ,valid : Bool, ande.Holds w:e.valid = true → w.isFinite = true ∧ |w.toReal - e.value| ≤ e.bound(the flag carries the range hypothesis).Est.contract sub a b pa pb, the estimate of a contractedfadd(fsubifsub) ofaandbwith factorspa,pb. Withs = ±1andMthe largest finite value ((posMaxFinite fmt).toReal): valueexact a pa + s · exact b pb; boundcontract_error's, the maximum over the three choices (unfused, fused witha's factors, fused withb's) of their factors' rounding errors plus half an ULP at the choice's exact result; valid iffaandbare finite and each choice's exact result,a + s·b,exact a pa + s·banda + s·exact b pb, has magnitude at mostM.RsqrtClose a won binary32:wis finite and|w.toReal - 1 / √a| ≤ rsqrtErr / √a. Two runs' results ofrsqrtare related when both areRsqrtCloseat the operand's value.Val.Lift t R v v':v = v', orv = .ofFloat t a,v' = .ofFloat t a'andR a a'.Respects R S C oforo : List Val → Nat → Except Fault Val: for every operand lists related elementwise byR(List.Forall₂) and oracle numbersn,n'withC n n',o xs nando ys n'are related byExcept.Rel S(the same fault, or values related byS).floatOp t op fm:floatBin t op fm x y none none non[x, y], a fault on other lists: the operation with no recorded factor.
Row 1 (floatOp_finEq). For every float type t, op ∈ {fadd, fsub, fmul} and flags fm
with nnan = false and ninf = false:
Respects (Val.Lift t FinEq) (Val.Lift t FinEq) (fun _ _ => True) (floatOp t op fm).
Proof.
FinEq.deliver: ifFinEq r r'thenFinEq (deliver r n) (deliver r' n')for everyn,n'. Ifr = r', the deliveries areNaNEq(NaNEq.deliver), and a NaN is not finite (Model.isFinite_eq_false_of_isNaN, throughGPUProof.UpToNaN.mono); if neither is finite, neither delivery is (not_finite_deliver).FinEq.op: forfwhose finite results have finite operands,FinEq x x'andFinEq y y'giveFinEq (f x y) (f x' y'). If both pairs are equal, the results are. Otherwise one ofx, x'(say) is not finite on both sides, so neither result is finite. FloatLib gives the premise foradd,subandmulon IEEE formats (Model.isFinite_of_isFinite_add,_sub,_mul), and everyFloatTy.fmtis IEEE (isIEEE_fmt, by cases). It is the case ofGPUProof.UpToNaN.map₂at the words that are not finite.floatBin_ofFloat: on two float scalars of typet, with flags that passFastMath.checkand have nonnanorninf, and no factors,floatBinis.ok (.ofFloat t (deliver (f a b) (n / 3)))withfbin op = some f, forfadd,fsub,fmulandfdiv:contract sub a b none none nis the unfused operation for everyn(no arm of its match fires without a factor), andwithFlagsreturns its argument when no flag poisons.- The row. If
fmfailsFastMath.check, both sides are that fault. Otherwise take the operand lists: of length other than 2 on both sides, both are the same fault. For[x, y]and[x', y']: write each pair as equal scalars that are not floats of typet, or as floats (an equal pair that is a float of typetis a float pair withFinEq a a). If either pair is not floats of typet, its scalar is the same on both sides, andfloatBin's result does not depend on the other operand's float or on the oracle number (floatBin_left,floatBin_right): undef faults, poison gives poison, and any other scalar faults as the wrong type. If both are floats, step 3 and steps 1-2 giveVal.Lift t FinEq.
Row rsqrt.approx (rsqrt_close). For every positive binary32 x that is finite, not zero
and not subnormal, and every n: RsqrtClose x.toReal (rsqrt x n).
Proof. Let w := rsqrt x n; rsqrtOk x w (rsqrtOk_of_rsqrt). Its arms for a NaN, a zero or
subnormal, a negative and an infinite x do not fire, so x.toRat? = some a and
w.toRat? = some b with rsqrtNear a b. Then
w is finite (Model.Algebraic.toRat?_isSome_eq_isFinite), a = x.toReal and b = w.toReal
(Model.Algebraic.toReal_of_toRat?_eq_some), 0 < a since x is not negative and not zero
(Model.toReal_nonneg_of_signBit_eq_false, Model.isZero_eq_true_iff_toReal_eq_zero), and
rsqrtNear_iff gives the bound. So for every two oracle numbers the two results are both
RsqrtClose at x.toReal: a free coupling. They need not be equal: rsqrt 1 is the word of 1 or
of 1 + 2 ^ -23.
Row maxnum / minnum, free (maxnum_of_not_nan). For every format, max flag, words x,
y with no signaling NaN ((x.isSignaling || y.isSignaling) = false) and not both NaNs, and every n:
maxnum max x y n = if max then maximumNumber x y else minimumNumber x y. So two runs give equal
words under any two oracle numbers; the condition "neither operand is a NaN" is a special case.
Proof. The first arm of maxnum needs a signaling NaN operand, so maxnum max x y n is
deliver r (n / 2) with r FloatLib's maximumNumber x y or minimumNumber x y. r is not a NaN
when not both operands are (Model.isNaN_maximumNumber_eq_false_of_not_both, _minimumNumber_),
so deliver returns it (deliver_of_isNaN_eq_false).
Row maxnum / minnum, coupled (maxnum_nanEq). For every format, max, x, y and oracle
numbers n, n' with n % 2 = n' % 2: NaNEq (maxnum max x y n) (maxnum max x y n'). The two
runs have the same operands x, y: the input relation is equality, not NaNEq (see the
counterexample after T5's statement).
Proof. NaNEq.deliver: NaNEq r r' gives NaNEq (deliver r n) (deliver r' n') for every n, n'
(a NaN is delivered as a NaN, isNaN_deliver, and a word that is not a NaN as itself;
FinEq.deliver goes through it). With n % 2 = n' % 2 both sides take the same arm of maxnum:
deliver of the canonical NaN, or deliver of one word r, at n / 2 and n' / 2;
NaNEq.deliver with r = r closes both. The results need not be equal: deliver picks the NaN
by n / 2.
Rows maxnum / minnum at the intrinsic, on scalars (intrinsic_fminmax_ofFloat,
fminmax_of_not_nan, fminmax_nanEq). For every max, type t whose element type is the float
type ft, words a, b of ft, context c, scope s and flags fm, the call of llvm.maxnum
(max) or llvm.minnum on the scalars .ofFloat ft a and .ofFloat ft b, as intrinsic
evaluates it, returns the scalar of maxnum max a b (s.ch 0), or poison if withFlags fm makes
it poison, and leaves s.mem (intrinsic_fminmax_ofFloat). So, free (fminmax_of_not_nan): with
no signaling NaN operand and not both NaNs the result is that of maximumNumber a b or
minimumNumber a b, with no oracle number; and coupled (fminmax_nanEq): with flags without
nnan and ninf, two scopes whose oracle numbers 0 have one parity give results related by
Val.Lift ft NaNEq, each leaving its scope's memory.
Proof. lanes2 on two scalars applies its function at lane 0, and floats2 reads a and b
back (Val.float?_ofFloat), so the call returns withFlags fm [a, b] (maxnum max a b (s.ch 0))
as a scalar, or poison. The free row rewrites maxnum by maxnum_of_not_nan; the coupled row
removes the flags by withFlags_some and relates the words by maxnum_nanEq. Instances and twins:
fminmax_inst and fminmax_twin in MojoProofTest/FloatRel.lean; the twins of the flag premises
are maxnum_skel's.
Rows maxnum / minnum at the intrinsic, on vectors (intrinsic_fminmax_vec,
fminmax_vec_of_not_nan, fminmax_vec_nanEq). For every max, type t whose element type is the
float type ft, lists of words as, bs of ft of one length, context c, scope s and flags
fm, the call on the vectors .vec (as.map (.ofFloat ft)) and .vec (bs.map (.ofFloat ft))
returns the vector whose lane j, of the words a, b, is the scalar of
maxnum max a b (s.ch j), or poison if withFlags fm makes it poison, and leaves s.mem
(intrinsic_fminmax_vec). So, free (fminmax_vec_of_not_nan): if no lane has a signaling NaN
operand or two NaN operands, lane j is the scalar of maximumNumber a b or minimumNumber a b
(or poison), with no oracle number; and coupled lane by lane (fminmax_vec_nanEq): with flags
without nnan and ninf, two scopes s, s' with s.ch j % 2 = s'.ch j % 2 for every lane
j < as.length give vectors xs, ys with List.Forall₂ (Val.Lift ft NaNEq) xs ys, each
leaving its scope's memory. The parity of oracle number 0 alone (the scalar row's premise) does
not suffice: lane 1 reads s.ch 1.
Proof. lanes2 on two vectors of one length maps its function over the zipped lanes with their
indices (List.zipIdx), in Except; the lists of scalars are maps of the word lists, so the
zip of the maps is the map of the zip (List.zip_map, List.zipIdx_map, List.mapM_map), and
floats2 reads each lane's words back (Val.float?_ofFloat), so each lane's function returns
pure of its scalar (mapM_congr), and List.mapM_pure gives the vector. The free row rewrites
maxnum lane by lane by maxnum_of_not_nan (a lane ((a, b), j) of the indexed zip has
(a, b) in the zip, List.fst_mem_of_mem_zipIdx; the indices dropped, List.zipIdx_map_fst).
The coupled row writes both vectors as maps of one indexed list (List.forall₂_map_left_iff,
List.forall₂_map_right_iff, List.forall₂_same); a lane ((a, b), j) has j < as.length
(List.mem_zipIdx), so its oracle numbers have one parity, and withFlags_some and
maxnum_nanEq relate the lane's scalars. Instances and twins: fminmax_vec_inst,
fminmax_vec_coupled and fminmax_vec_twin in MojoProofTest/FloatRel.lean.
Row: the error relation, one operation (contract_est, floatBin_contract_est). For every
IEEE format, sub, words a, b with IsProd a pa and IsProd b pb
(each operand is a rounded product of its factors, if it has them) and every oracle number n:
(Est.contract sub a b pa pb).Holds (contract sub a b pa pb n) (contract_est). For every float
type t, op ∈ {fadd, fsub}, flags with contract and every n, if floatBin t op fm on the
scalars of a and b, with the scalars of the factors, gives the scalar of r, then
(Est.contract (op == fsub) a b pa pb).Holds r (floatBin_contract_est). Free: no condition on the
oracle numbers, so two runs' results are both within the bound of the same value.
Proof.
- Finiteness. Assume the estimate is valid.
contract_casesgives three cases. Unfused:add a borsub a bof finite operands whose exact result has magnitude at mostMis finite (FloatLib'sModel.isFinite_add_of_abs_toReal_add_le_posMaxFinite,_sub_). Fused witha's factors(u, v):ais finite, somul u vis (IsProd), souandvare (Model.isFinite_of_isFinite_mul;IsProd.factors_finite);±bis finite, and|u v ± b| = |exact a pa + s·b| ≤ M(withtoReal (neg b) = -toReal bfor finiteb), sofma u v (±b)is finite (Model.isFinite_fma_of_abs_toReal_fma_le_posMaxFinite). Fused withb's factors(c, d): the same,fma (±c) d awith|±c d + a| = |a + s·exact b pb| ≤ M. - The bound:
contract_error, whose premise is the finiteness of 1. - At
floatBin(holds_withFlags). A valid estimate that holds of the IEEE resultcmakescfinite, so not a NaN, sodeliver c k = c;withFlagsreturns its argument or nothing, so a valuerit returns isc.floatBinwithcontract(flags withoutnsz,reassoc,arcp,afn; with them it faults) on the scalars ofa,band their factors computeswithFlags fm [a, b] (deliver (contract (op == fsub) a b pa pb n) (n / 3)), and readsrback from its scalar (Model.ofBits_toBits), as infloatBin_contract; 1-2 and this step close it.
The validity flag is a condition on the operands' values, not on the result word; it is decidable
on rationals but Est.contract takes it on reals (decide on ℝ, so noncomputable), since the
operands' estimates along a term are real intervals.
Row: NaN (fbin_isNaN, floatOp_isNaN). For every IEEE format,
operator op with an IEEE 754 operation (fadd, fsub, fmul, fdiv; fbin op = some f) and
words x, y one of which is a NaN, f x y is a NaN (fbin_isNaN). For every float type t,
operator other than frem, flags without nsz, reassoc, arcp, afn (with them floatBin
faults), nnan and ninf (contract is allowed), words a, b one of which is a NaN and every
oracle number k, floatOp t op fm on their scalars gives the scalar of a NaN
(floatOp_isNaN).
Proof. FloatLib's Proof.add_eq_spec (and sub_, mul_, div_) rewrites each operation to its
specification. Spec.add x y matches on toDyadic? x, toDyadic? y; a NaN has no dyadic value
(toDyadic?_eq_none_of_isNaN), so the first arm is impossible and the result is chooseNaN2 x y's
NaN: chooseNaN2 is none only if neither operand is a NaN (chooseNaN2_eq_none_iff), and what it
returns is a NaN (isNaN_of_chooseNaN2_eq_some). Spec.sub x y is Spec.add x (neg y), and neg
keeps a NaN a NaN (isNaN_neg). Spec.mul has add's shape; Spec.div falls through to
divSpecial, which matches on chooseNaN2 first. At floatBin (floatBin_ofFloat): the result
is deliver (f a b) (k / 3), which withFlags returns unchanged when neither nnan nor ninf is
set, and deliver keeps a NaN a NaN (isNaN_deliver). FloatLib v4.1.0 has no such lemma; these
lines answer FloatLib request 1 (NaN propagation) on our side. Instances and twins: nan_row_inst,
nan_row_twin in MojoProofTest/FloatRel.lean.
Row: NaN equivalence under free oracles (floatOp_nanEq). For every float type t, operator
op other than frem (fadd, fsub, fmul, fdiv) and flags fm with nnan = false and
ninf = false:
Respects (Val.Lift t NaNEq) (Val.Lift t NaNEq) (fun _ _ => True) (floatOp t op fm).
Proof. Row 1's steps 3 and 4 do not use FinEq, so they are proved once, for every relation R
on the floats of t that relates each float to itself (floatOp_lift): if fbin op = some f and
R x x', R y y' give R (deliver (f x y) n) (deliver (f x' y') n') for every n, n', then
floatOp t op fm respects Val.Lift t R under any two oracle numbers. Row 1 is floatOp_lift with
FinEq.op and FinEq.deliver. For this row:
fbin_some: every operator butfremhas an IEEE operationf(by cases).NaNEq.op:NaNEq x x'andNaNEq y y'giveNaNEq (f x y) (f x' y'). If both pairs are equal, the results are. Otherwise one pair (sayx, x') are both NaNs, and the NaN row (fbin_isNaN) makes both results NaNs.NaNEq.deliver(proved above) for every two oracle numbers, thenfloatOp_lift.
Instance and twin (nanEq_row_inst, MojoProofTest/FloatRel.lean): fadd of the two quiet NaNs
0x7fc00000 and 0x7fc00001 with 1, under the oracle numbers 0 and 5, gives related results;
the operand relation cannot be FinEq: fadd of +∞ and 1 and of a quiet NaN and 1 (operands
related by FinEq) gives +∞ and a NaN, which NaNEq does not relate.
Rows left, and why.
- The error relation is proved for one operation on words with known values (above); along a term,
as a
Respectsstatement, the operands are themselves estimated results, andEstmust be computed from their estimates (the value, the bound and the validity flag propagated, with the operands' errors added to the bound), which is not proved.
Instances and twins (MojoProofTest/FloatRel.lean, binary32, by evaluation; three of them are counterexamples):
FinEq:+∞and a NaN areFinEq; the contracted results+0and-2 ^ -46ofcontract false (mul a b) (-1) (some (a, b)) none nforn = 0, 1(a = 1 + 2 ^ -23,b = 1 - 2 ^ -23) are not, so row 1 fails for a recorded factor under free oracles.NaNEq: two NaNs are;maxnum true sNaN 1 nforn = 1, 0, a NaN and 1, are not, somaxnumwith a NaN operand does not respectNaNEqunder free oracles.maxnum, free row:maxnum true 1 2 nis 2 andmaxnum true qNaN 1 nis 1 for everyn; the twin of the premise on signaling NaNs isnanEq_inst's pair (sNaNand 1 under 1 and 0 give a NaN and 1); the twin of the premise "not both NaNs":maxnum true qNaN qNaN' nundern = 2 · 0x7fc00000andn = 2 · 0x7fc00001gives the two different NaNs0x7fc00000and0x7fc00001.maxnum, coupled row:maxnum true sNaN 1 nundern = 1andn = 2 · 0x7fc00001 + 1, of one parity, gives two different NaNs, which areNaNEq; the twin of the coupling isnanEq_inst's pair (n = 1andn = 0).maxnumat the intrinsic, on<2 x float>vectors with no flags:<1, qNaN>and<2, 1>give<2, 1>under every scope (fminmax_vec_inst);<sNaN, 1>and<1, 2>under two scopes whose oracle numbers 0 and 1 have one parity each give lanes related byVal.Lift NaNEq(fminmax_vec_coupled). Twins (fminmax_vec_twin): of the coupling lane by lane,<1, sNaN>and<2, 1>under two scopes whose oracle numbers 0 are both 0 and whose oracle numbers 1 are 1 and 0 give lanes 1 that are a NaN and 1, not related; of the premise "no lane has two NaN operands",<qNaN, 1>and<qNaN', 2>under oracle numbers 02 · 0x7fc00000and2 · 0x7fc00001give two different NaNs at lane 0.Est:⟨-2 ^ -46, 2 ^ -46, true⟩holds of both contracted results; with bound 0 it holds of the fused one and not the unfused one; withvalid = falseit holds of a NaN.- The error relation's row:
fadd contractofmul a b(with its factorsa = 1 + 2 ^ -23,b = 1 - 2 ^ -23) and-1, asfloatBinevaluates it, givesct nforn = 0, 1, 2; itsEst.contractis valid with valuea b - 1 = -2 ^ -46, so eachct nis finite and within the bound of-2 ^ -46(contract_est_inst). The twin of the validity flag:fadd contractof the largest finite binary32 number with itself gives+∞; its estimate is not valid (|2M| > M), and with the flag set the estimate would not hold of+∞, which is not finite (contract_est_twin). The premisesIsProdhave no twin here. RsqrtClose: both values ofrsqrt 1(the words of 1 and of1 + 2 ^ -23) are close at 1 byrsqrt_close, and they differ, sorsqrtdoes not respect equality under free oracles; the word of1 + 2 ^ -22is not close at 1.- Row 1 on scalars:
floatOp float fadd {}on[+∞, 1]and[NaN, 1]gives two results that areVal.Lift FinEq; its twin withnnan: on the same operands one result is poison and the other a float, whichVal.Lift FinEqdoes not relate; its twin on the operator:fdivof 1 by+∞and by a NaN gives+0and a NaN, whichVal.Lift FinEqdoes not relate, sofdivis not in row 1 (divhas finite results with an operand that is not finite).
Composition
Fix a launch, arguments and address choice ch. Run once on a reference payload (m₁, ω₁) to a
grid that is done and not bad (Grid.run, certified by evaluation). Then for every m₂ with
Mem.SkelEq pay m₁ m₂ and every ω₂:
- T3 (
Grid.payload_runwith T3b) gives a run on(m₂, ω₂)to a gridz₂that is done and not bad, andGrid.start_soundgives the six fields ofGrid.Soundthat do not mentionR; - T4 gives
obs z₂.memas the output terms evaluated on(m₂, ω₂); - T5 with FloatLib gives
Rof it, which is the seventh field.
This is Kernel.Sound for every payload in the class and every admitted oracle, at ch. The
quantifier over ch stays. It is discharged by the block checker on a run that is
symbolic in the address atoms; that is out of scope here.
The six-field lemma (MojoProof/Sem/SkelStep.lean, proved)
Grid.skel_six is the first two steps for the unit payload, for every program, kernel, launch,
arguments, labelling, payload blocks, address choice and pair of memories and oracles that meet
its premises. From one start Grid.start prog fn L args m₁ ch o₁ = .ok (g₁, c₁) with
m₁.BytesIn m₁.Known, Labels.Ok prog lab = true, fn found in prog, lab.MemOk pay L c₁ g₁
and one run ReflTransGen (Grid.Step L c₁) g₁ z₁ to a grid z₁ that is done and not bad: for
every m₂ with m₁.SkelEq pay m₂ and every o₂, the launch on (m₂, o₂) starts at some
(g₂, c₂) with Grid.Sound L c₂ g₂ (fun m => some m.blocks) (fun _ => True).
- With the trivial relation the field
postholds wheneverdeterminatedoes, so the content is the first six fields. The observation is the blocks, the strongest one: with the unit observationdeterminatewould say nothing. - Proof:
Grid.skel_run(one use ofGrid.sound_of_one_run, throughGrid.payload_runandGrid.start_sound) at the observationfun m => some m.blocks. Grid.Sound.of_blocksgives the seventh field for any observationobsthat reads only the blocks and anyR: from soundness for the blocks and one final gridzreachable fromgwithobs z.mem = some yandR y,Grid.Sound L c g obs R.- No case split on a float value or the oracle. The proof closure of
Grid.skel_six(theorem values, matchers and auxiliary definitions; 8,203 constants, 4,375 theorems) has no theorem of FloatLib, Sem/Float.lean or Sem/FloatRel.lean. The only float-typed matchers in it are 8 splits onOption (Model _), whether a decode or a lookup of an operation succeeded (floatBin.match_8,_10,_13,floats2.match_1,fnegV.match_1,intrinsic.match_1,_6,_8), and it has no recursor of a FloatLib type. The controlrsqrtOk_rSqrthas 746 FloatLib theorems in its closure. - Instances (MojoProofTest/PayloadRun.lean):
six_instonkF(load float,fadd, store) for every word in block 1 and every oracle, from the one run on 1.0 with oracle 0;sum_inst, the seventh field for bytes 0 to 3 of block 1 and 2.0 at 1.0 and oracle 0.
What a kernel's proof must give for the premises: Labels.Ok and the lookup by evaluation; the
first memory's BytesIn (its pointer bytes point into its blocks); Labels.MemOk, that the
pointer of every payload load and store points into a block of pay at every grid reachable from
the start (the hard premise; for kF it is checked by ScheduleOwned.every, which does not scale
to vector_addition on L23); and the reference run, done and not bad.
Dependencies
- In the tree:
Grid.Step,GPUProof.Badatsig,Grid.Sound,Path,Path.exists_iff;Grid.start_sound(T2's conclusion 2);exec,step,enter,Grid.advance,Grid.fire;Mem.load,Mem.store,Mem.check,Mem.fresh,castV,Layout.decode,Layout.encode,Thread.pending,exists_deliver.
- Defined for T3a:
Grid.Agree,Grid.Lockstepand the five statements above (no semantics). - Defined for T3b:
Val.erase,Val.Skel,MemByte.erase,MemByte.Skel,Block.SkelEq,Mem.SkelEq,Labels,Labels.Rel,Labels.Ok,Labels.MemOk,Frame.Skel,Thread.Skel,Status.Skel,Grid.SkelReland the lemmas listed. - T3c and T4: the block summaries and
Block.sound. T5:SVal,SVal.eval.
Instances and twins
- T3a, for every launch, contexts and grid:
Grid.Lockstep L c c Eq. This instance is a theorem over all grids. The twin of the fieldtrace: a relation that agrees on every step and onDonebut relates two grids with different traces does not preserveBad. Example:doneP, with a racy trace, anddone2. - T3b's run, given:
run_inst(MojoProofTest/SkelStep.lean),Grid.skel_runon the one-step runs ofkernel #[](ret void) onmemX 1andmemX 2, which differ in the data byte 0 of block 1, the payload block; the ends are related and the second start is sound for that byte. Twinrun_twin: with no payload block, no one-step run onmemX 2ends at a grid related to the first's end. That instance has no payload operation; the next one has. - T3b's run on a kernel that reads and writes the payload, given:
run_inst(MojoProofTest/PayloadRun.lean),Grid.skel_runonkF,%1 = load float, ptr %0,%2 = fadd float %1, %1,store float %2, ptr %0, launched on one thread onmemF w1, block 1 holding 1.0, the payload block, with address choice and oracle 0. The run of four steps ends with 2.0 in block 1; for every memory related tomemF w1and every second oracle, the second run of four steps ends at a related done grid that is not bad, and the second start is sound for the size of block 1. The load is evaluated after unfoldingLayout.decodeonce;Labels.MemOkneeds register 0 to point into block 1 at every reachable grid, whichScheduleOwned.everychecks from the grid after the load. One example: one kernel, one first memory, address choice 0 and first oracle 0. Twinrun_twin: the read-onlymemF w1 trueis not related tomemF w1, and no run of four steps on it ends at a done grid, as its store faults. - The twins of T3b's premises:
- (O1): a branch on
fcmpof an oracle-chosen word stores in one run and not in the other, so the traces differ. MemOk: a payload store into a block outsidepaybreaksMem.SkelEq.- Same
ch, counterexample (iii), given asaddr_twin(MojoProofTest/Skeleton.lean): fromstart2's grid, thread 0'salloca i32underc2and underc2'(address choice 1 everywhere) makes block 2 at address 0 and at address 4, so the memories are notMem.SkelEqfor anypay. Aptrtointof theallocaand a branch on it would then take different edges in the two runs.
- (O1): a branch on