Docs / Proofs

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):

Scope.

Which corpus kernels pass Labels.Ok is not claimed here, except vector_addition (vadd_ok, MojoProofTest/Labels.lean). Expected, and not checked:

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.

  1. T3 is split in two:
    • T3a: a lockstep bisimulation between the grids of two context families carries runs, Done and Bad, and Grid.Sound for observations it preserves, for every relation.
    • T3b: the skeleton relation Grid.SkelRel is such a bisimulation for a labelled program.
  2. 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.Ok checks 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.MemOk on 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.
  3. 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, range on payload). Their domain conditions become hypotheses on both runs, stated on T4's terms.
  4. 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_sound applies 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₂:

Proof

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:

Status.Skel relates statuses with one constructor:

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.

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):

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 ω₁, ω₂:

Lemmas used (to prove unless marked proved)

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):

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.

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]:

The second is a load fed to a phi whose result decides a branch, written as an AST (phiFn):

Two runs (for every labelling lab, payload blocks pay, table and pair of valuations).

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.

Statements.

  1. vals_rel: under valuations related by Valuation.Rel, meeting LoadsOk under the first, on a table whose nodes pass payOk, every node's value is related at its role: one fault, or equal values where the role is skeleton and values related by Val.Skel where it is payload.
  2. SEff.run_rel: with values related as in (1), each effect's pointer with one value under both (Summary.oblivious_skel) and StoresOk, the effects give one fault or memories related by Mem.SkelEq pay.
  3. Valuation.after_rel: from oblivious, agrees, LoadsOk, payOk and StoresOk, (V₁.after S).Rel lab pay (V₂.after S).
  4. Valuation.into_rel: with agreesI lab V₁.fn l S in place of agrees, (V₁.into l S).Rel lab pay (V₂.into l S).

Proof.

  1. Induction on the table (vals_snoc, roles_snoc), as vals_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 by Valuation.Rel.regs, a node by induction, a constant equal), so by Val.Skel (Labels.Rel.to), and by payOk:
    • bin: lanes2_skel with intBin_skel (the second operand is equal when skelB);
    • icmp: icmpV_skel; integer casts: lanes_skel with intCast_skel; extractvalue: extractV_skel;
    • float operations: lanes2_skel with floatBin_skel (any oracle numbers and fmul contract operands);
    • call, getelementptr: one value, as in SNode.eval_skel;
    • load: one pointer q; Mem.load_skel (with Ty.data) gives related values, so Val.Skel.defined gives one noundef check. A fault is the same fault on both sides: Except.Rel relates .error e only to .error e.
  2. Except.Rel.foldlM from Valuation.Rel.mem. Each effect's pointer has one value, so one address q. A load effect records one event (Mem.log_skel). A store writes values related at the value operand's role: equal if skeleton; if payload, related by Val.Skel, and StoresOk puts q in pay; so Mem.store_skel applies.
  3. Field by field. Context and function: after keeps V's. Memory: (2), or V's memories when the effects fault in both. Register r (regVal): if the block sets it, its entry x has values related at x's role (1), and agrees gives a payload label when that role is payload (Labels.Rel.mono); if not, V's registers. fmul contract operands (regProd): none for a register the block sets, V's otherwise.
  4. into is after except for an exit into blocks with phis (Exit.phi) whose condition selects a target d, and oblivious_skel gives one d under both. There enter runs from the frames Valuation.frameAt, related by Frame.Skel by (3), and evaluates each phi's operand for l in each run's scope (one layout and globals by Valuation.Rel). An operand that mentions no endPay register 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 by Valuation.Rel.regs if not. Otherwise phiAgrees gives a register with a payload result, and its values are related by Val.Skel (evalV_pay). Frame.Skel.setAll and Frame.Skel.goto give related frames (enter_rel), so related registers and operands (enter_fields: the function is kept). A fault of enter is one fault in both runs, and into is then after.

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):

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.

Statements.

  1. Valuation.last_rel: if V₁.Rel lab pay V₂, V₁.fn = fn, pathOk and V₁.PathMem hold, 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.
  2. Block.sound_ret_rel: for two contexts of one program and two threads of one frame each at block l's position p0, whose frames have one list of allocas (premise ha), if coversPathWith false accepts the path, pathOk holds, each obligation of the path passes Cond.effsIn at its block's summary (premise hd), the first entry valuation meets WalkWith false, the last block returns, the entry valuations are related and the first meets PathMem, 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's allocas made dead) are related by Mem.SkelEq pay.
  3. Cond.holds_rel: for valuations related by Valuation.Rel and a summary S that is oblivious, passes payOk and meets LoadsOk and StoresOk under the first, every obligation d with Cond.effsIn S d that holds under the first on S's node values holds under the second.
  4. WalkWith.rel: if V₁.Rel lab pay V₂, V₁.fn = fn, pathOk holds, every obligation of the path passes Cond.effsIn at its block's summary, and V₁.PathMem holds, then WalkWith false from V₁ gives WalkWith false from V₂.

Proof.

  1. Induction on ps. A one-block path: pathOk gives oblivious, agreesI (so agrees, its first conjunct) and payOk at fn = V₁.fn, and PathMem gives LoadsOk and StoresOk, so Valuation.after_rel. A longer path: Valuation.into_rel relates 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.
  2. Block.sound_retWith for each thread (the second's program and function are the first's by Valuation.Rel, and its last block is the first's by (1)): each run's steps reach the last block's end on the memory me that its effects make from its entry valuation (SEff.run), and the next step returns. That memory is Valuation.after's, so (1) relates the two. The return sets each block of the frame's allocas dead in turn (List.foldl of Mem.setLive b false); with one list in both frames (ha), Mem.foldl_setLive_skel (MojoProof/Sem/Skeleton.lean; induction on the list, Mem.setLive_skel at each block) relates the returned memories. The second run's WalkWith false is (4)'s.
  3. vals_rel relates the node values. Cond.ok x: SVal.eval_rel relates x's results (Except.Rel: one fault or two values), so an ok under the first is an ok under the second. Cond.bool x: the two values are related by Val.Skel at least (Labels.Rel.to), which keeps a scalar's width (Val.Skel.scalar); a word under the first is a word under the second, as poison and undef are not defined (Val.Skel.defined). Cond.mem es: each effect is one of S.effs (Cond.effsIn), whose pointers are one under both (Summary.oblivious_skel) and whose payload stores write to pay (StoresOk), so SEff.run_rel gives one fault or related memories.
  4. 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 by Valuation.into_rel and 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):

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:

T3c: partial payload operations (after T4)

The partial operations are:

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):

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:

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:

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:

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:

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.

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:

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.

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.

  1. FinEq.deliver: if FinEq r r' then FinEq (deliver r n) (deliver r' n') for every n, n'. If r = r', the deliveries are NaNEq (NaNEq.deliver), and a NaN is not finite (Model.isFinite_eq_false_of_isNaN, through GPUProof.UpToNaN.mono); if neither is finite, neither delivery is (not_finite_deliver).
  2. FinEq.op: for f whose finite results have finite operands, FinEq x x' and FinEq y y' give FinEq (f x y) (f x' y'). If both pairs are equal, the results are. Otherwise one of x, x' (say) is not finite on both sides, so neither result is finite. FloatLib gives the premise for add, sub and mul on IEEE formats (Model.isFinite_of_isFinite_add, _sub, _mul), and every FloatTy.fmt is IEEE (isIEEE_fmt, by cases). It is the case of GPUProof.UpToNaN.map₂ at the words that are not finite.
  3. floatBin_ofFloat: on two float scalars of type t, with flags that pass FastMath.check and have no nnan or ninf, and no factors, floatBin is .ok (.ofFloat t (deliver (f a b) (n / 3))) with fbin op = some f, for fadd, fsub, fmul and fdiv: contract sub a b none none n is the unfused operation for every n (no arm of its match fires without a factor), and withFlags returns its argument when no flag poisons.
  4. The row. If fm fails FastMath.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 type t, or as floats (an equal pair that is a float of type t is a float pair with FinEq a a). If either pair is not floats of type t, its scalar is the same on both sides, and floatBin'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 give Val.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.

  1. Finiteness. Assume the estimate is valid. contract_cases gives three cases. Unfused: add a b or sub a b of finite operands whose exact result has magnitude at most M is finite (FloatLib's Model.isFinite_add_of_abs_toReal_add_le_posMaxFinite, _sub_). Fused with a's factors (u, v): a is finite, so mul u v is (IsProd), so u and v are (Model.isFinite_of_isFinite_mul; IsProd.factors_finite); ±b is finite, and |u v ± b| = |exact a pa + s·b| ≤ M (with toReal (neg b) = -toReal b for finite b), so fma u v (±b) is finite (Model.isFinite_fma_of_abs_toReal_fma_le_posMaxFinite). Fused with b's factors (c, d): the same, fma (±c) d a with |±c d + a| = |a + s·exact b pb| ≤ M.
  2. The bound: contract_error, whose premise is the finiteness of 1.
  3. At floatBin (holds_withFlags). A valid estimate that holds of the IEEE result c makes c finite, so not a NaN, so deliver c k = c; withFlags returns its argument or nothing, so a value r it returns is c. floatBin with contract (flags without nsz, reassoc, arcp, afn; with them it faults) on the scalars of a, b and their factors computes withFlags fm [a, b] (deliver (contract (op == fsub) a b pa pb n) (n / 3)), and reads r back from its scalar (Model.ofBits_toBits), as in floatBin_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:

  1. fbin_some: every operator but frem has an IEEE operation f (by cases).
  2. NaNEq.op: NaNEq x x' and NaNEq y y' give NaNEq (f x y) (f x' y'). If both pairs are equal, the results are. Otherwise one pair (say x, x') are both NaNs, and the NaN row (fbin_isNaN) makes both results NaNs.
  3. NaNEq.deliver (proved above) for every two oracle numbers, then floatOp_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.

Instances and twins (MojoProofTest/FloatRel.lean, binary32, by evaluation; three of them are counterexamples):

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 ω₂:

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).

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

Instances and twins